having error when trying to MYSQL server in Android - java

hello i am learning to connect android application with MYSQL using this tutorial.. Tutorial
i want to login and add some comments to the MYSQL database in my hosting.
i have done all the steps correctly. but when i try to load the application in the phone .that say "unfortunately the MYSQL has stopped working" and gives me the following error.
can some one help me to fix this error please. thank you....
Full error stack
02-08 15:21:43.578: E/AndroidRuntime(9705): FATAL EXCEPTION: AsyncTask #1
02-08 15:21:43.578: E/AndroidRuntime(9705): java.lang.RuntimeException: An error occured while executing doInBackground()
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.lang.Thread.run(Thread.java:838)
02-08 15:21:43.578: E/AndroidRuntime(9705): Caused by: java.lang.NullPointerException
02-08 15:21:43.578: E/AndroidRuntime(9705): at lk.adspace.mysqltest.Login$AttemptLogin.doInBackground(Login.java:141)
02-08 15:21:43.578: E/AndroidRuntime(9705): at lk.adspace.mysqltest.Login$AttemptLogin.doInBackground(Login.java:1)
02-08 15:21:43.578: E/AndroidRuntime(9705): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-08 15:21:43.578: E/AndroidRuntime(9705): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-08 15:21:43.578: E/AndroidRuntime(9705): ... 4 more
02-08 15:21:43.928: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:43.985: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:44.342: D/OpenGLRenderer(9705): Flushing caches (mode 1)
02-08 15:21:44.345: D/InputMethodManager(9705): deactivate the inputconnection in ControlledInputConnectionWrapper.
02-08 15:21:44.355: D/OpenGLRenderer(9705): Flushing caches (mode 0)
02-08 15:21:44.363: E/WindowManager(9705): Activity lk.adspace.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41344e60 V.E..... R......D 0,0-456,144} that was originally added here
02-08 15:21:44.363: E/WindowManager(9705): android.view.WindowLeaked: Activity lk.adspace.mysqltest.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41344e60 V.E..... R......D 0,0-456,144} that was originally added here
02-08 15:21:44.363: E/WindowManager(9705): at android.view.ViewRootImpl.<init> (ViewRootImpl.java:409)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:218)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:70)
02-08 15:21:44.363: E/WindowManager(9705): at android.app.Dialog.show(Dialog.java:281)
02-08 15:21:44.363: E/WindowManager(9705): at lk.adspace.mysqltest.Login$AttemptLogin.onPreExecute(Login.java:110)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.AsyncTask.execute(AsyncTask.java:534)
02-08 15:21:44.363: E/WindowManager(9705): at lk.adspace.mysqltest.Login.onClick(Login.java:83)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.View.performClick(View.java:4212)
02-08 15:21:44.363: E/WindowManager(9705): at android.view.View$PerformClick.run(View.java:17476)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Handler.handleCallback(Handler.java:800)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Handler.dispatchMessage(Handler.java:100)
02-08 15:21:44.363: E/WindowManager(9705): at android.os.Looper.loop(Looper.java:194)
02-08 15:21:44.363: E/WindowManager(9705): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-08 15:21:44.363: E/WindowManager(9705): at java.lang.reflect.Method.invokeNative(Native Method)
02-08 15:21:44.363: E/WindowManager(9705): at java.lang.reflect.Method.invoke(Method.java:525)
02-08 15:21:44.363: E/WindowManager(9705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-08 15:21:44.363: E/WindowManager(9705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-08 15:21:44.363: E/WindowManager(9705): at dalvik.system.NativeStart.main(Native Method)
02-08 15:21:44.364: D/OpenGLRenderer(9705): Flushing caches (mode 0)
here is my login.java file
package lk.adspace.mysqltest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://www.adspace.lk/webservice/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
//Intent i = new Intent(Login.this, ReadComments.class);
//finish();
//startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
}
}
}
JSONParser.java file
package lk.adspace.mysqltest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public JSONObject makeHttpRequest(String loginUrl, String string,
List<NameValuePair> params) {
// TODO Auto-generated method stub
return null;
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="lk.adspace.mysqltest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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" >
<activity
android:name="lk.adspace.mysqltest.Login"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="lk.adspace.mysqltest.Register"
android:label="#string/app_name" >
</activity>
<activity
android:name="lk.adspace.mysqltest.AddComment"
android:label="#string/app_name" >
</activity>
<activity
android:name="lk.adspace.mysqltest.ReadComments"
android:label="#string/app_name" >
</activity>
</application>
</manifest>

Start your new activity on onPostExecute method instead on doInBackground
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);

Related

Choose activity dynamically during splashscreen

I'm doing a small project, and today I had to make a conditional validation in splashscreen. The project was practically finalized when we decided to do this validation in splashscreen.
Modified my class and was working ok, but I had to include the time for the splash disappears (variable SPLASH_TIME_OUT) and started giving an error that I do not understand.
My splashscreen clas (now) is:
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new PesquisaVoto().execute();
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
int SPLASH_TIME_OUT = 2000;
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
} else {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
The error I am getting is:
03-03 17:38:49.882 10432-10450/com.clubee.vote D/Create Response﹕ {"voto":[{"count":"1"}],"success":1}
03-03 17:38:49.882 10432-10450/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 17:38:49.892 10432-10450/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 10432
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done
Anyone knows what I did wrong? Is it possivel to implement the Runnable inside the IF statement? If I do not put the timeout variable, everything is right.
UPDATE THE LOG WITH ERROR
03-03 22:01:50.016 18731-18746/com.clubee.vote W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x4164dd88)
03-03 22:01:50.026 18731-18746/com.clubee.vote E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.clubee.vote, PID: 18731
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:87)
at com.clubee.vote.Splashscreen$PesquisaVoto.doInBackground(Splashscreen.java:48)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:841)
03-03 22:01:50.697 18731-18731/com.clubee.vote E/WindowManager﹕ android.view.WindowLeaked: Activity com.clubee.vote.Splashscreen has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{44aa2458 V.E..... R......D 0,0-681,345} that was originally added here
at android.view.ViewRootImpl.(ViewRootImpl.java:350)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:294)
at com.clubee.vote.Splashscreen$PesquisaVoto.onPreExecute(Splashscreen.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.clubee.vote.Splashscreen.onCreate(Splashscreen.java:44)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2201)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2286)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1246)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:212)
at android.app.ActivityThread.main(ActivityThread.java:5135)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
at dalvik.system.NativeStart.main(Native Method)
03-03 22:01:52.529 18731-18746/com.clubee.vote I/Process﹕ Sending signal. PID: 18731 SIG: 9
Tks in advance for answers and comments. I corrected my code, re-wrote and re-structured it, became easier to see where the mistakes were.
below, I leave the code that is working for future research. thank you very much
package com.clubee.vote;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Splashscreen extends Activity {
// Splash screen timer
private static String url_Pesquisa_voto = "http://dev.clubee.com.br/dbvote/PesquisaVoto.php";
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";
private static int SPLASH_TIME_OUT = 2000;
public String retrieveMacAddress(Context context) {
WifiManager wfman = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac address ou wi-fi desabilitado";
}
return macAddress;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new PesquisaVoto().execute();
}
}, SPLASH_TIME_OUT);
}
class PesquisaVoto extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Splashscreen.this);
pDialog.setMessage("Pesquisando Voto..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
WifiManager wfman = (WifiManager) getSystemService(Context.WIFI_SERVICE);
String macAddress = wfman.getConnectionInfo().getMacAddress();
if (macAddress == null) {
macAddress = "Dispositivo sem endereço mac";
}
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("macAddress", macAddress));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_Pesquisa_voto, "GET", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Intent i = new Intent(Splashscreen.this, ResultadoFalho.class);
startActivity(i);
}
else {
Intent i = new Intent(Splashscreen.this, MainActivity.class);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
}
}
}
I cannot clearly see what is wrong based on the Logs you provided but there is something wrong with your structure.
You are starting an Activity within doInBackground Process and then dismissing the Progress Dialog which belongs to the Activity that you just finished.
Try to pass a parameter to the onPostExecute and then finish your Activity there.
And post some more details from your Log to make it clear. There has to be some more logs indicating what went wrong.

Android custom Camera application crashes as it starts "unfortuantely stopped"

I am trying to build my own custom camera application I have learn through the Android developers Group about how to code the whole application but as soon as I launch the camera it crashes I don't know what is the problem here is my code:
package com.example.tapeit;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Files.FileColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
public class CameraActivity extends Activity implements Camera.PictureCallback {
private Camera mCamera;
private CameraPreview mPreview;
String TAG = "TapeIt";
public static final int MEDIA_TYPE_IMAGE = 1;
Button captureButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_layout);
mCamera = getCameraInstance();
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(preview);
captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
}
});
}
private boolean checkCameraHardware(Context context){
if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
return true;
}else{
return false;
}
}
public static Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open();
} catch (Exception e) {
}
return c;
}
private PictureCallback mPicture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: " );
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
private static File getOutputMediaFile(int mediaTypeImage) {
// TODO Auto-generated method stub
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraApp");
if(! mediaStorageDir.exists()){
if(! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
return mediaFile;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: " );
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
}
And here is my preview Class:
package com.example.tapeit;
import java.io.IOException;
import android.content.Context;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.hardware.Camera;
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private Camera mCamera;
private SurfaceHolder mHolder;
String TAG = "TapeIt";
public CameraPreview (Context context, Camera camera){
super(context);
mCamera = camera;
mHolder = getHolder();
mHolder.addCallback(this);
}
public void surfaceCreated(SurfaceHolder holder){
try{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(IOException e){
Log.d(TAG, "Error setting camera preview" + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// TODO Auto-generated method stub
if(mHolder.getSurface() == null){
return;
}
try{
mCamera.stopPreview();
}catch(Exception e){
}
//You should make here changes when the device is rotated or when any other change
// set preview size and make any resize, rotate or
// reformatting changes here
//mCamera.getParameters().getSupportedPreviewSizes();
try{
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
}catch(IOException e){
Log.d(TAG, "Error setting camera preview" + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
}
My manifest uses all the permision here they are:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.camera" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.tapeit.CameraActivity"
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>
My logcat in the console is posted here:
04-04 11:19:32.010: D/AndroidRuntime(21270): Shutting down VM
04-04 11:19:32.010: W/dalvikvm(21270): threadid=1: thread exiting with uncaught exception (group=0x40eb72a0)
04-04 11:19:32.010: E/AndroidRuntime(21270): FATAL EXCEPTION: main
04-04 11:19:32.010: E/AndroidRuntime(21270): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tapeit/com.example.tapeit.CameraActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.access$700(ActivityThread.java:134)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.os.Looper.loop(Looper.java:137)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.main(ActivityThread.java:4867)
04-04 11:19:32.010: E/AndroidRuntime(21270): at java.lang.reflect.Method.invokeNative(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): at java.lang.reflect.Method.invoke(Method.java:511)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
04-04 11:19:32.010: E/AndroidRuntime(21270): at dalvik.system.NativeStart.main(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addViewInner(ViewGroup.java:3439)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3310)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3255)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.view.ViewGroup.addView(ViewGroup.java:3231)
04-04 11:19:32.010: E/AndroidRuntime(21270): at com.example.tapeit.CameraActivity.onCreate(CameraActivity.java:39)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.Activity.performCreate(Activity.java:5047)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
04-04 11:19:32.010: E/AndroidRuntime(21270): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
04-04 11:19:32.010: E/AndroidRuntime(21270): ... 11 more
preview.addView(preview);
You are attempting to add the FrameLayout to itself. This will not work.
Presumably, the parameter should be mPreview.
You may wish to use more distinctive names for variables, such as not having both preview and mPreview.

Activity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView

I am experiencing this error on this AddRestaurantActivity
This is my AddRestaurantActivity.java file. This is code for the activity which updates the database and creates a new restaurant with goggle geo places latitude and longitude. In the emulator when I press the Create button to create the restaurant the app dies (unfortunately Restaurant finder has stopped). And the error in the logcat is found underneath
package admin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.mad.restaurantfinderrm.R;
import com.mad.restaurantfinderrm.library.DatabaseHandler;
import com.mad.restaurantfinderrm.library.JSONParser;
import com.mad.restaurantfinderrm.library.UserFunctions;
public class AddRestaurantActivity extends Activity {
UserFunctions userFunctions;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputType;
EditText inputBio;
EditText inputAddressLine1;
EditText inputAddressLine2;
EditText inputAddressLine3;
EditText inputContactNum;
EditText inputEmail;
EditText inputMenuUrl;
// url to create new Restaurant
// private static String url_create_restaurant =
// "http://192.168.0.10/~robertmcnamara/RestaurantFinderAPI/createRestaurant.php";
private static String url_create_restaurant = "http://askme- jobs.com/api/createRestaurant.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
static Double lat;
static Double lng;
// DB
private SQLiteDatabase mDb;
private Cursor mCursor;
String user_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_restaurant);
userFunctions = new UserFunctions();
// getting user_id
DatabaseHandler mh = new DatabaseHandler(getApplicationContext());
mDb = mh.getWritableDatabase();
mCursor = mDb.query("login", null, null, null, null, null, null);
if (mCursor != null && mCursor.getCount() > 0) {
mCursor.moveToFirst();
user_id = mCursor.getString(mCursor.getColumnIndex("uid"));
}
// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputType = (EditText) findViewById(R.id.inputType);
inputBio = (EditText) findViewById(R.id.inputBio);
inputAddressLine1 = (EditText) findViewById(R.id.inputAddress1);
inputAddressLine2 = (EditText) findViewById(R.id.inputAddress2);
inputAddressLine3 = (EditText) findViewById(R.id.inputAddress3);
inputContactNum = (EditText) findViewById(R.id.inputContactNum);
inputEmail = (EditText) findViewById(R.id.inputEmail);
inputMenuUrl = (EditText) findViewById(R.id.inputMenuUrl);
// Create button
Button btnCreateRestaurant = (Button) findViewById(R.id.btnCreateRestaurant);
// button click event
btnCreateRestaurant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (inputName.getText().toString().trim().contentEquals("")
|| inputType.getText().toString().trim()
.contentEquals("")
|| inputBio.getText().toString().trim()
.contentEquals("")
|| inputAddressLine1.getText().toString().trim()
.contentEquals("")
|| inputAddressLine2.getText().toString().trim()
.contentEquals("")
|| inputContactNum.getText().toString().trim()
.contentEquals("")
|| inputEmail.getText().toString().trim()
.contentEquals("")
|| inputMenuUrl.getText().toString().trim()
.contentEquals("")) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
AddRestaurantActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Input validation");
// Setting Dialog Message
alertDialog
.setMessage("Please enter all details again,\nmaking sure they are correct");
// Setting Icon to Dialog
// alertDialog.setIcon(android.R.drawable.delete);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
} else {
// creating new product in background thread
new CreateNewRestaurant().execute();
}
}
});
}
#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, menu);
return true;
}
/*
* Event Handling for Individual menu item selected Identify single menu
* item by it's id
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_logout:
// logout user
// TODO check Internet here?
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
// Closing dashboard screen
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/**
* Background Async Task to Create new Restaurant
* */
class CreateNewRestaurant extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AddRestaurantActivity.this);
pDialog.setMessage("Creating Restaurant..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating Restaurant
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String type = inputType.getText().toString();
String bio = inputBio.getText().toString();
String addressLine1 = inputAddressLine1.getText().toString();
String addressLine2 = inputAddressLine2.getText().toString();
String addressLine3 = inputAddressLine3.getText().toString();
String phoneNum = inputContactNum.getText().toString();
String email = inputEmail.getText().toString();
String menuUrl = inputMenuUrl.getText().toString();
// img
// String img = "";
String fullAddress = name + ", " + addressLine1 + ", "
+ addressLine2 + ", " + addressLine3;
Geocoder geoCoder = new Geocoder(getApplicationContext());
List<Address> addressList;
try {
addressList = geoCoder.getFromLocationName(fullAddress, 1);
Address address = addressList.get(0);
if (address.hasLatitude() && address.hasLongitude()) {
lat = address.getLatitude();
lng = address.getLongitude();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.v("LAT", lat.toString());
Log.v("LNG", lng.toString());
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("type", type));
params.add(new BasicNameValuePair("bio", bio));
params.add(new BasicNameValuePair("addressLine1", addressLine1));
params.add(new BasicNameValuePair("addressLine2", addressLine2));
params.add(new BasicNameValuePair("addressLine3", addressLine3));
params.add(new BasicNameValuePair("contactNumber", phoneNum));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("lat", lat.toString()));
params.add(new BasicNameValuePair("lng", lng.toString()));
params.add(new BasicNameValuePair("url", menuUrl));
params.add(new BasicNameValuePair("user_id", user_id));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_restaurant,
"POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(),
ViewRestaurantActivity.class);
i.putExtra("MESSAGE", "add");
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
overridePendingTransition(R.anim.slide_in_top,
R.anim.slide_out_bottom);
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Error in logcat :
01-22 07:50:28.381: E/WindowManager(924): Activity com.mad.restaurantfinderrm.TabsViewPagerFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41891c88 V.E..... R.....I. 0,0-240,147} that was originally added here
01-22 07:50:28.381: E/WindowManager(924): android.view.WindowLeaked: Activity com.mad.restaurantfinderrm.TabsViewPagerFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41891c88 V.E..... R.....I. 0,0-240,147} that was originally added here
01-22 07:50:28.381: E/WindowManager(924): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345)
01-22 07:50:28.381: E/WindowManager(924): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239)
01-22 07:50:28.381: E/WindowManager(924): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
01-22 07:50:28.381: E/WindowManager(924): at android.app.Dialog.show(Dialog.java:281)
01-22 07:50:28.381: E/WindowManager(924): at com.mad.restaurantfinderrm.Tab2Fragment.error(Tab2Fragment.java:248)
01-22 07:50:28.381: E/WindowManager(924): at com.mad.restaurantfinderrm.Tab2Fragment.displayDeals(Tab2Fragment.java:324)
01-22 07:50:28.381: E/WindowManager(924): at com.mad.restaurantfinderrm.Tab2Fragment$LoadDeals$1.run(Tab2Fragment.java:209)
01-22 07:50:28.381: E/WindowManager(924): at android.app.Activity.runOnUiThread(Activity.java:4673)
01-22 07:50:28.381: E/WindowManager(924): at com.mad.restaurantfinderrm.Tab2Fragment$LoadDeals.onPostExecute(Tab2Fragment.java:183)
01-22 07:50:28.381: E/WindowManager(924): at com.mad.restaurantfinderrm.Tab2Fragment$LoadDeals.onPostExecute(Tab2Fragment.java:1)
01-22 07:50:28.381: E/WindowManager(924): at android.os.AsyncTask.finish(AsyncTask.java:631)
01-22 07:50:28.381: E/WindowManager(924): at android.os.AsyncTask.access$600(AsyncTask.java:177)
01-22 07:50:28.381: E/WindowManager(924): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
01-22 07:50:28.381: E/WindowManager(924): at android.os.Handler.dispatchMessage(Handler.java:99)
01-22 07:50:28.381: E/WindowManager(924): at android.os.Looper.loop(Looper.java:137)
01-22 07:50:28.381: E/WindowManager(924): at android.app.ActivityThread.main(ActivityThread.java:5103)
01-22 07:50:28.381: E/WindowManager(924): at java.lang.reflect.Method.invokeNative(Native Method)
01-22 07:50:28.381: E/WindowManager(924): at java.lang.reflect.Method.invoke(Method.java:525)
01-22 07:50:28.381: E/WindowManager(924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-22 07:50:28.381: E/WindowManager(924): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-22 07:50:28.381: E/WindowManager(924): at dalvik.system.NativeStart.main(Native Method)
You are calling finish() before onPostExecute is called. I think this will leak your pDialog. Try moving finish() in the onPostExecute after dismissing the pDialog

Unfortunately app has stopped working [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I am new to android application development. I was doing this tutorial app.
When I run it in the emulator ,it says "Unfortunately AndroidJSONParsingActivity has stopped working.
" There are no errors in the code. The API level is 17 and the emulator is Nexus S.
Please help me out.
I got the tutorial CODE from JSON tutorial
AndroidJsonParsing.java
package com.example.androidjsonparsingactivity;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsing extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}
JSONParser.java
package com.example.androidjsonparsingactivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
SingleMenuItemActivity.java
package com.example.androidjsonparsingactivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_PHONE_MOBILE = "mobile";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String name = in.getStringExtra(TAG_NAME);
String cost = in.getStringExtra(TAG_EMAIL);
String description = in.getStringExtra(TAG_PHONE_MOBILE);
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.email_label);
TextView lblDesc = (TextView) findViewById(R.id.mobile_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(description);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidjsonparsingactivity"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.androidjsonparsingactivity.AndroidJSONParsing"
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=".SingleListItem"
android:label="Single Item Selected"></activity>
</application>
</manifest>
Logcat
08-01 07:32:35.531: D/dalvikvm(1121): GC_FOR_ALLOC freed 42K, 7% free 2609K/2792K, paused 37ms, total 41ms
08-01 07:32:35.541: I/dalvikvm-heap(1121): Grow heap (frag case) to 3.288MB for 635812-byte allocation
08-01 07:32:35.591: D/dalvikvm(1121): GC_FOR_ALLOC freed 2K, 6% free 3227K/3416K, paused 47ms, total 47ms
08-01 07:32:35.672: D/dalvikvm(1121): GC_CONCURRENT freed <1K, 6% free 3237K/3416K, paused 9ms+16ms, total 82ms
08-01 07:32:35.740: D/AndroidRuntime(1121): Shutting down VM
08-01 07:32:35.740: W/dalvikvm(1121): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-01 07:32:35.761: E/AndroidRuntime(1121): FATAL EXCEPTION: main
08-01 07:32:35.761: E/AndroidRuntime(1121): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidjsonparsingactivity/com.example.androidjsonparsingactivity.AndroidJSONParsing}: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.Looper.loop(Looper.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.lang.reflect.Method.invoke(Method.java:511)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-01 07:32:35.761: E/AndroidRuntime(1121): at dalvik.system.NativeStart.main(Native Method)
08-01 07:32:35.761: E/AndroidRuntime(1121): Caused by: android.os.NetworkOnMainThreadException
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
08-01 07:32:35.761: E/AndroidRuntime(1121): at java.net.InetAddress.getAllByName(InetAddress.java:214)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-01 07:32:35.761: E/AndroidRuntime(1121): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.JSONParser.getJSONFromUrl(JSONParser.java:38)
08-01 07:32:35.761: E/AndroidRuntime(1121): at com.example.androidjsonparsingactivity.AndroidJSONParsing.onCreate(AndroidJSONParsing.java:54)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Activity.performCreate(Activity.java:5104)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-01 07:32:35.761: E/AndroidRuntime(1121): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-01 07:32:35.761: E/AndroidRuntime(1121): ... 11 more
For Android 4.0 and above you cant do network operations on UI Thread and need to use background threads.
You are calling the following code from the main thread instead of
background thread therefore this exception is thrown .
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
Instead create a async task and perform this in the doInBackground() of the async task
Async task performs the opertaion in background instead of performing it on the main /UI thread
class FetchJsonTask extends AsyncTask<Void, Void, void> {
protected Void doInBackground(Void... params) {
try {
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
} catch (Exception e) {
}
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//code to be executed after background task is finished
}
protected void onPreExecute() {
super.onPreExecute();
//code to be executed before background task is started
}
return null;
}
In onCreate() call the execute the async task in the following way :
new FetchJsonTask().execute();
Related Link:
How to fix android.os.NetworkOnMainThreadException?
you have called the Web from main thread. that's why you have got
Caused by: android.os.NetworkOnMainThreadException
after android 4.0 you cant do network operations on its UIThread. you need to use background threads. i will prefer to use AsyncTask for network call.
Hope it Helps!!
read commented parts and change your code according to that.
class MyAsync extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
// do your JSON parse here
return null;
}
#Override
protected void onPostExecute(Void result) {
// after gettin json data do whatever you want here
super.onPostExecute(result);
}
}
call your async class in your oncreate as:
new MyAsync().execute();

Google Drive SDK Activity Not Found Exception

I am trying to implement Stephen Wylie's Google Drive example (here). Here is my code:
package com.googledrive.googledriveapp;
// For Google Drive / Play Services
// Version 1.1 - Added new comments & removed dead code
// Stephen Wylie - 10/20/2012
import java.io.IOException;
import java.util.ArrayList;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
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;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Apps.List;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveRequest;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class MainActivity extends Activity {
private static final int CHOOSE_ACCOUNT=0;
private static String accountName;
private static int REQUEST_TOKEN=0;
private Button btn_drive;
private Context ctx = this;
private Activity a = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set up the GUI layout
setContentView(R.layout.activity_main);
// set the variables to access the GUI controls
btn_drive = (Button) findViewById(R.id.btn_drive);
btn_drive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
chooseAccount();
}
});
}
public void chooseAccount() {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, CHOOSE_ACCOUNT);
}
// Fetch the access token asynchronously.
void getAndUseAuthTokenInAsyncTask(Account account) {
AsyncTask<Account, String, String> task = new AsyncTask<Account, String, String>() {
ProgressDialog progressDlg;
AsyncTask<Account, String, String> me = this;
#Override
protected void onPreExecute() {
progressDlg = new ProgressDialog(ctx, ProgressDialog.STYLE_SPINNER);
progressDlg.setMax(100);
progressDlg.setTitle("Validating...");
progressDlg.setMessage("Verifying the login data you entered...\n\nThis action will time out after 10 seconds.");
progressDlg.setCancelable(false);
progressDlg.setIndeterminate(false);
progressDlg.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface d) {
progressDlg.dismiss();
me.cancel(true);
}
});
progressDlg.show();
}
#Override
protected String doInBackground(Account... params) {
return getAccessToken(params[0]);
}
#Override
protected void onPostExecute(String s) {
if (s == null) {
// Wait for the extra intent
} else {
accountName = s;
getDriveFiles();
}
progressDlg.dismiss();
}
};
task.execute(account);
}
/**
* Fetches the token from a particular Google account chosen by the user. DO NOT RUN THIS DIRECTLY. It must be run asynchronously inside an AsyncTask.
* #param activity
* #param account
* #return
*/
private String getAccessToken(Account account) {
try {
return GoogleAuthUtil.getToken(ctx, account.name, "oauth2:" + DriveScopes.DRIVE_READONLY); // IMPORTANT: DriveScopes must be changed depending on what level of access you want
} catch (UserRecoverableAuthException e) {
// Start the Approval Screen intent, if not run from an Activity, add the Intent.FLAG_ACTIVITY_NEW_TASK flag.
a.startActivityForResult(e.getIntent(), REQUEST_TOKEN);
e.printStackTrace();
return null;
} catch (GoogleAuthException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Drive getDriveService() {
HttpTransport ht = AndroidHttp.newCompatibleTransport(); // Makes a transport compatible with both Android 2.2- and 2.3+
JacksonFactory jf = new JacksonFactory(); // You need a JSON parser to help you out with the API response
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accountName);
HttpRequestFactory rf = ht.createRequestFactory(credential);
Drive.Builder b = new Drive.Builder(ht, jf, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setOauthToken(accountName);
}
});
return b.build();
}
/**
* Obtains a list of all files on the signed-in user's Google Drive account.
*/
private void getDriveFiles() {
Drive service = getDriveService();
Log.d("SiteTrack", "FUNCTION getDriveFiles()");
Files.List request;
try {
request = service.files().list(); // .setQ("mimeType=\"text/plain\"");
} catch (IOException e) {
e.printStackTrace();
return;
}
do {
FileList files;
try {
Log.d("SiteTrack", request.toString());
files = request.execute();
} catch (IOException e) {
e.printStackTrace();
Log.d("SiteTrack", "Exception");
return;
}
ArrayList<File> fileList = (ArrayList<File>) files.getItems();
Log.d("SiteTrack", "Files found: " + files.getItems().size());
for (File f : fileList) {
String fileId = f.getId();
String title = f.getTitle();
Log.d("SiteTrack", "File " + fileId + ": " + title);
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() >= 0);
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == CHOOSE_ACCOUNT && resultCode == RESULT_OK) {
accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
GoogleAccountManager gam = new GoogleAccountManager(this);
getAndUseAuthTokenInAsyncTask(gam.getAccountByName(accountName));
Log.d("SiteTrack", "CHOOSE_ACCOUNT");
} else if (requestCode == REQUEST_TOKEN && resultCode == RESULT_OK) {
accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.d("SiteTrack", "REQUEST_TOKEN");
}
}
}
Here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.googledrive.googledriveapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="android.app.ActivityGroup" />
</activity>
</application>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_drive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect to Google Drive" />
</LinearLayout>
And here is the LogCat error I receive. It occurs when the button is pressed:
10-28 00:25:28.637: E/AndroidRuntime(842): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.google.android.gms.common.account.CHOOSE_ACCOUNT (has extras) }
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1512)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.Activity.startActivityForResult(Activity.java:3190)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.googledrive.googledriveapp.MainActivity.chooseAccount(MainActivity.java:67)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.googledrive.googledriveapp.MainActivity$1.onClick(MainActivity.java:60)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.view.View.performClick(View.java:3511)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.view.View$PerformClick.run(View.java:14105)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.os.Handler.handleCallback(Handler.java:605)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.os.Handler.dispatchMessage(Handler.java:92)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.os.Looper.loop(Looper.java:137)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.ActivityThread.main(ActivityThread.java:4424)
10-28 00:25:28.637: E/AndroidRuntime(842): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 00:25:28.637: E/AndroidRuntime(842): at java.lang.reflect.Method.invoke(Method.java:511)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-28 00:25:28.637: E/AndroidRuntime(842): at dalvik.system.NativeStart.main(Native Method)
Can anyone help out?
We've been doing some experimenting, and our current theory is that the new Google OAuth Library depends on having the latest version of Google Play.
We found that if your device still has the Android Marketplace, or an older Google Play we couldn't get OAuth to work.
So you might try opening the Android Marketplace or Google Play App to kick off an upgrade.
Open the Android Marketplace, Accept the Upgrade to Google Play.
Close the Marketplace, and open the Google Play App.
Accept the Terms of Service for Google Play.
Wait a few seconds, sacrifice a chicken, and then you should be able to run Google OAuth.
EDIT: Looks like Google Provides some guidance on what your app should do if your users are missing the correct Google Play version. See: https://developer.android.com/google/play-services/setup.html#ensure
Google Drive API seems (acording to the Google people) to only works on a real Device, in the Emulator it will crash with this error.
So my Advice, try on a real device.

Categories

Resources