Android unable to add getByName - java

I'm trying to add getByName to get the IP address of a hostname and use it in my POST command
the problem is wherever i insert this code it crashes
i tried to insert in doInBackground it also crashes So where should i insert it ??
package com.example.loginad;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Logindb extends Activity {
Button login;
EditText u,p;
TextView res;
String result;
String x="mobile";
String host;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logindb);
login=(Button)findViewById(R.id.login);
u=(EditText)findViewById(R.id.u);
p=(EditText)findViewById(R.id.p);
res=(TextView)findViewById(R.id.res);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new MyAsyncTask().execute(u.getText().toString(),p.getText().toString());
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
boolean success = postData(params[0],params[1]);
try
{
InetAddress address=null;
address = InetAddress.getByName("Nicky-PC");
host=address.getHostAddress();
}
catch(Exception e)
{
e.printStackTrace();
}
return success;
}
protected void onPostExecute(Boolean localres){
if (localres){
res.setText("A Correct Username and Password");
}else{
res.setText("Incorrect Username or Password");
}
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
//pb.setProgress(progress[0]);
//Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_LONG).show();
}
/*public void ObtainHost()
{
try
{
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} */
public Boolean postData(String a,String b) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", a));
postParameters.add(new BasicNameValuePair("password", b));
postParameters.add(new BasicNameValuePair("mobileid",x));
// String valid = "1";
String response = null;
try {
// Toast.makeText(getApplicationContext(), host.toString(), Toast.LENGTH_LONG).show();
response = CustomHttpClient.executeHttpPost("http://"+host+"/new/check.php",postParameters);
//now in result you will have the response from php file either 0 or 1.
result = response.toString();
// res = res.trim();
result = result.replaceAll("\\s+", "");
// error.setText(res);
} catch (Exception e) {
res.setText(e.toString());
}
return result.equals("1");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logindb, menu);
return true;
}
}
Stacktrace
11-26 21:28:37.856: D/libEGL(17150): loaded /system/lib/egl/libEGL_genymotion.so
11-26 21:28:37.876: D/(17150): HostConnection::get() New Host Connection established 0xb8ed35a8, tid 17150
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-26 21:28:37.900: D/libEGL(17150): loaded /system/lib/egl/libGLESv2_genymotion.so
11-26 21:28:37.968: W/EGL_genymotion(17150): eglSurfaceAttrib not implemented
11-26 21:28:37.976: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from GradienCache
11-26 21:28:37.996: E/OpenGLRenderer(17150): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
11-26 21:28:37.996: D/OpenGLRenderer(17150): Enabling debug mode 0
11-26 21:28:44.876: W/dalvikvm(17150): threadid=13: thread exiting with uncaught exception (group=0xa4c1f648)
11-26 21:28:44.920: E/AndroidRuntime(17150): FATAL EXCEPTION: AsyncTask #3
11-26 21:28:44.920: E/AndroidRuntime(17150): java.lang.RuntimeException: An error occured while executing doInBackground()
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.lang.Thread.run(Thread.java:841)
11-26 21:28:44.920: E/AndroidRuntime(17150): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5908)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:837)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:358)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.view.View.requestLayout(View.java:15792)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.checkForRelayout(TextView.java:6524)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3771)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3629)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.widget.TextView.setText(TextView.java:3604)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.postData(Logindb.java:130)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:70)
11-26 21:28:44.920: E/AndroidRuntime(17150): at com.example.loginad.Logindb$MyAsyncTask.doInBackground(Logindb.java:1)
11-26 21:28:44.920: E/AndroidRuntime(17150): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-26 21:28:44.920: E/AndroidRuntime(17150): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-26 21:28:44.920: E/AndroidRuntime(17150): ... 4 more
11-26 21:28:44.932: D/dalvikvm(17150): GC_FOR_ALLOC freed 259K, 5% free 6365K/6660K, paused 8ms, total 8ms

First if you will use AsyncHttpClient then you do not need AsyncTask but if you will use HttpClient then you need AsyncTask task.
the below code is part from working code to execute get and post requests. Modify it as your need
#Override
protected String doInBackground(String... params) {
backGroundExecuted = false;
Log.d("doInBackground", "Start processing doInBackground");
HttpClient httpClient = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
if (httpMethodType == null || url == null) {
Log.d("doInBackground" , "The URL and Method Type is mandatory, cannot be null - httpMethodType =" + httpMethodType + " and url =" + url);
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("The URL and Method Type is mandatory, cannot be null");
return null;
}
try {
//set timeout
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, TIME_OUT);
HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIME_OUT);
httpClient = new DefaultHttpClient(httpParameters);
HttpResponse httpResponse = null;
if (httpMethodType.equals(HTTPMethodType.POST.toString())) {
httpPost = new HttpPost(url);
//setting json object to request.
if (postParams != null) {
AbstractHttpEntity entity = null;
entity = new ByteArrayEntity(postParams.getBytes("UTF8"));
if (httpContentType != null) {
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, httpContentType));
}
httpPost.setEntity(entity);
}
httpResponse = httpClient.execute(httpPost);
} else if (httpMethodType.equals(HTTPMethodType.GET.toString()) || httpMethodType.equals(HTTPMethodType.PUT.toString())) {
if (queryParams != null) {
url = url + "?" + URLEncodedUtils.format(queryParams, "utf-8");
Log.d(TAG ,"new URL :" + url);
}
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
this.getApiResponse().setResponseCode(httpResponse.getStatusLine().getStatusCode());
this.getApiResponse().setResponseDescription(httpResponse.getStatusLine().getReasonPhrase());
if (this.getApiResponse().getResponseCode() != HttpStatus.SC_OK) {
this.getApiResponse().setSuccess(false);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseCode() + " for URL " + url);
Log.w(getClass().getSimpleName(),
"Error " + this.getApiResponse().getResponseDescription() + " for URL " + url);
}
Log.d("doInBackground", "The API call executed and will check the response");
HttpEntity entityResp = httpResponse.getEntity();
if (entityResp != null) {
this.getApiResponse().setResponse(appHelper.getStringFromInputStream(entityResp.getContent()));
Log.d("doInBackground","The response is :" + this.getApiResponse().getResponse());
this.getApiResponse().setSuccess(true);
}
} catch (UnsupportedEncodingException e1) {
Log.e("doInBackground","Exception :" + e1.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e1.toString());
Log.e("doInBackground","Exception :" + e1.toString());
e1.printStackTrace();
} catch (Exception e) {
Log.e("doInBackground","Exception :" + e.toString());
this.getApiResponse().setSuccess(false);
this.getApiResponse().setResponseCode(HttpResponseCode.BAD_REQUEST);
this.getApiResponse().setResponseDescription("Exception :" + e.toString());
if (httpPost != null && !httpPost.isAborted()) {
httpPost.abort();
}
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
backGroundExecuted = true;
}
return null;
}

Related

Sending String to PHP file via android application

I am developing an app which includes the upload of all contacts to my server what i am doing is displaying all the contacts and sending them to my server as a string.Here is my code:
package com.example.core.freemusic;
import java.io.IOException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
public class MainActivity extends Activity {
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ll = (LinearLayout) findViewById(R.id.LinearLayout1);
LoadContactsAyscn lca = new LoadContactsAyscn();
lca.execute();
}
class LoadContactsAyscn extends AsyncTask < Void, Void, String > {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(MainActivity.this, "Please Wait","");
}
#Override
protected String doInBackground(Void...params) {
String contacts = "";
Cursor c = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (c.moveToNext()) {
String contactName = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phNumber = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts += contactName + ":" + phNumber + "\n";
}
c.close();
return contacts;
}
#Override
protected void onPostExecute(String contacts) {
super.onPostExecute(contacts);
pd.cancel();
TextView a = (TextView) findViewById(R.id.textView);
a.setText(contacts);
doInBackground(contacts);
}
protected void doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
try {
httpclient.execute(httppost);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Actually the code shows no error but on running it in emulator it crashes.
the error on logcat is:
05-24 14:00:57.989 2488-2500/com.example.core.freemusic W/art﹕ Suspending all threads took: 5.841ms
05-24 14:00:57.992 2488-2500/com.example.core.freemusic I/art﹕ Background partial concurrent mark sweep GC freed 1888(115KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 502KB/1014KB, paused 6.923ms total 95.188ms
05-24 14:00:58.073 2488-2488/com.example.core.freemusic I/Choreographer﹕ Skipped 37 frames! The application may be doing too much work on its main thread.
05-24 14:00:58.080 2488-2488/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
05-24 14:00:58.102 2488-2488/com.example.core.freemusic D/AndroidRuntime﹕ Shutting down VM
05-24 14:00:58.103 2488-2488/com.example.core.freemusic E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.core.freemusic, PID: 2488
java.lang.IllegalArgumentException: Illegal character in query at index 43: http://192.168.2.30/b.php?username=Sd:(546) 456-4826
Sad:486-44
at java.net.URI.create(URI.java:730)
at org.apache.http.client.methods.HttpPost.<init>(HttpPost.java:79)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:64)
at com.example.core.freemusic.MainActivity$LoadContactsAyscn.onPostExecute(MainActivity.java:38)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
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)
05-24 14:01:01.259 2488-2488/com.example.core.freemusic I/Process﹕ Sending signal. PID: 2488 SIG: 9
05-24 15:24:12.790 2685-2685/com.example.core.freemusic D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
As error code state, you need to encode the query:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+params);
need to changed into:
HttpPost httppost = new HttpPost("http://192.168.2.30/b.php?username="+java.net.URLEncoder.encode(params[0], "UTF-8"));

Android HttpClient Two different httpposts not working?

I have the following code.
I want to post on the first time the user press a button that the data will be send to httpclient and will return data. This works fine (Button 1). When a user press button 1 it will give the right results.
Then I want to post a second time with different data to the httpclient. When a user press button 2. The data will be send to the function but the logs (see code) returns in the exceptions every time NULL. So I think it will not send to httpclient and will not fill the httppost with the data I want to send.
My question is, what do I wrong or do I forget?
Do I need to create a second httpclient handler?
Do I need to create a second httppost handler?
Please help.
Thank you.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import info.androidhive.customlistviewvolley.util.MyHttpClient;
public class Login extends Activity {
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
ProgressDialog offlineDialog = null;
String logged, token, valid;
String expired = "expired";
String status, responseContent = "0";
String msg = "";
public void onCreate(Bundle savedInstanceState) {
httpclient=new MyHttpClient(getApplicationContext());
httppost= new HttpPost("https://www.test.com/json/index.php");
b = (Button)findViewById(R.id.buttonLogin);
c = (Button)findViewById(R.id.shareData);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog = ProgressDialog.show(Login.this, "","Validating user...", true);
new Thread(new Runnable() {
public void run() {
login();
}
}).start();
}
});
String username = 'abc';
String password = 'xxx';
String token = '12321abcksadkm';
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
offlineDialog = ProgressDialog.show(Login.this, "", "Share content...", true);
new Thread(new Runnable() {
public void run() {
// This will be executed but will give NULL and offcourse no results
share.connectDP(username,password,"share","18228",token);
}
}).start();
}
});
}
void login(){
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",pass.getText().toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
public void connectDP(String username, String password, String action, String id, String token){
// This is passed, it returns the data = :)
Log.i("connect", "username" + username);
Log.i("connect", "password" + password);
Log.i("connect", "action" + action);
Log.i("connect", "id" + id);
Log.i("connect", "token" + token);
try{
final byte[] SALT;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
byte[] buf = new byte[20];
random.nextBytes(buf);
SALT = buf;
nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("username",username.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("password",password.toString().trim()));
nameValuePairs.add(new BasicNameValuePair("token",SALT.toString().trim()));
Log.i("Salt", "Key =" + SALT.toString().trim());
Log.i("test", "test" + nameValuePairs);
//// <!---- After here it will break, but no any error or warning -----!>
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
response=httpclient.execute(httppost);
String responseContent = EntityUtils.toString(response.getEntity());
//Log.d("Response", responseContent );
JSONObject jsonObject = new JSONObject(responseContent);
JSONArray jArray = jsonObject.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
try {
JSONObject json_data = jArray.getJSONObject(i);
logged = json_data.getString("status"); // obtain status
token = json_data.getString("token"); // obtain token
valid = json_data.getString("valid"); // obtain validation period
expired = "no";
Log.i("Logged JSON", "Result?" + json_data.getString("status"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
}
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ usernameabc
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ passwordxxx
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ actionshare
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ id18228
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/connect﹕ token12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/test 1﹕ test[username=abc, password=xxx, requestAction=share, requestFile=18228, load_remote_token=12321abcksadkm
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 1a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 2a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 3﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 4a﹕ testnull
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley D/test 5﹕ 0
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/System.out﹕ Exception : Value 0 of type java.lang.Integer cannot be converted to JSONObject
04-03 19:33:22.380 12220-12220/info.androidhive.customlistviewvolley I/Log share﹕ [ 04-03 19:33:25.390 169:0x204 W/InputManagerService ]
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#4156a2c8
package info.androidhive.customlistviewvolley.util;
import android.content.Context;
import info.androidhive.customlistviewvolley.R;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import java.io.InputStream;
import java.security.KeyStore;
import org.apache.http.conn.ssl.SSLSocketFactory;
public class MyHttpClient extends DefaultHttpClient {
final Context _context;
public MyHttpClient(Context context) {
this._context = context;
}
#Override
protected ClientConnectionManager createClientConnectionManager() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
// Register for port 443 our SSLSocketFactory with our keystore
// to the ConnectionManager
registry.register(new Scheme("https", (org.apache.http.conn.scheme.SocketFactory) newSslSocketFactory(), 443));
return new SingleClientConnManager(getParams(), registry);
}
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = _context.getResources().openRawResource(R.raw.keystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "xxxxxxxx".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
}
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ java.lang.NullPointerException
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.Login.connectDP(Login.java:247)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at info.androidhive.customlistviewvolley.adater.CustomGridOfflineMedia$2.onClick(CustomGridOfflineMedia.java:200)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View.performClick(View.java:3511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.view.View$PerformClick.run(View.java:14110)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:605)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4424)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
04-04 22:39:06.890 15395-15395/info.androidhive.customlistviewvolley W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
i hope somebody more qualified will answer your question soon, until then something to maybe look into:
HttpPost.reset inherited from AbstractExecutionAwareRequest
says in the docs:
"Resets internal state of the request making it reusable."
making me think that maybe if you do not reset the httppost object it isn't reusable...
src: http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/AbstractExecutionAwareRequest.html#reset()
According to the logcat, your API doesnt response a valid JSON format.
It must be "response" : "0" or something liek that instead of plain 0.
I suggest you to check the server side code for connectDB function and what it returns.
This has been solved by changing some code.

Reading a text file from res/raw folder

Im trying to read a text file from the raw folder in res using final Scanner input = new Scanner(new File(R.raw.xmlsource)).useDelimiter("[\\;]+"); but it isn't reading because of the resource id being int in R.java file, my code is below
EDIT Made some changes to my code below, still doesn't run but using the debugger i can tell that it actually reads the file, the problem seems to be at String[] RssLinksArray = readLine.split("[\\;]+"); where the code terminates, i can't for the life of me figure out why. i'm attaching the logcat also.
Any help would be tremendously appreciated.
package com.simplerssreader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.URL;
import java.util.List;
import java.util.Scanner;
import org.xmlpull.v1.XmlPullParserException;
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;
public class RssService extends IntentService
{
public static final String ITEMS = "items";
public static final String RECEIVER = "receiver";
public RssService()
{
super("RssService");
}
#Override
protected void onHandleIntent(Intent intent)
{
InputStream is = getResources().openRawResource(R.raw.xmlsource);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
while ((readLine = br.readLine()) != null)
{
}
} catch (IOException e)
{
e.printStackTrace();
}
String[] RssLinksArray = readLine.split("[\\;]+");
final String RSS_LINK = RssLinksArray[0];
Log.d(Constants.TAG, "Service started");
List<RssItem> rssItems = null;
try
{
XMLRssParser parser = new XMLRssParser();
rssItems = parser.parse(getInputStream(RSS_LINK));
}
catch (XmlPullParserException e)
{
Log.w(e.getMessage(), e);
}
catch (IOException e)
{
Log.w(e.getMessage(), e);
}
Bundle bundle = new Bundle();
bundle.putSerializable(ITEMS, (Serializable) rssItems);
ResultReceiver receiver = intent.getParcelableExtra(RECEIVER);
receiver.send(0, bundle);
}
public InputStream getInputStream(String link)
{
try
{
URL url = new URL(link);
return url.openConnection().getInputStream();
} catch (IOException e)
{
Log.w(Constants.TAG, "Exception while retrieving the input stream", e);
return null;
}
}
}
LOGCAT
10-24 23:07:49.908: D/dalvikvm(1189): GC_FOR_ALLOC freed 101K, 9% free 2778K/3040K, paused 68ms, total 72ms
10-24 23:07:49.938: I/dalvikvm-heap(1189): Grow heap (frag case) to 3.939MB for 1127536-byte allocation
10-24 23:07:50.089: D/dalvikvm(1189): GC_FOR_ALLOC freed 2K, 7% free 3877K/4144K, paused 149ms, total 149ms
10-24 23:07:50.461: W/dalvikvm(1189): threadid=11: thread exiting with uncaught exception (group=0x41465700)
10-24 23:07:50.504: E/AndroidRuntime(1189): FATAL EXCEPTION: IntentService[RssService]
10-24 23:07:50.504: E/AndroidRuntime(1189): java.lang.NullPointerException
10-24 23:07:50.504: E/AndroidRuntime(1189): at com.simplerssreader.RssService.onHandleIntent(RssService.java:48)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Handler.dispatchMessage(Handler.java:99)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.Looper.loop(Looper.java:137)
10-24 23:07:50.504: E/AndroidRuntime(1189): at android.os.HandlerThread.run(HandlerThread.java:61)
10-24 23:07:50.899: D/libEGL(1189): loaded /system/lib/egl/libEGL_emulation.so
10-24 23:07:50.940: D/(1189): HostConnection::get() New Host Connection established 0x2a1db628, tid 1189
10-24 23:07:51.078: D/libEGL(1189): loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-24 23:07:51.279: D/libEGL(1189): loaded /system/lib/egl/libGLESv2_emulation.so
10-24 23:07:51.699: W/EGL_emulation(1189): eglSurfaceAttrib not implemented
10-24 23:07:51.729: D/OpenGLRenderer(1189): Enabling debug mode 0
10-24 23:07:51.769: I/Choreographer(1189): Skipped 85 frames! The application may be doing too much work on its main thread.
10-24 23:07:56.358: I/Choreographer(1189): Skipped 265 frames! The application may be doing too much work on its main thread.
InputStream inputStream = getResources().openRawResource(R.raw.xmlsource);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

Send a string to a servlet from android

I am trying to send a string from a android application to a servlet and then retrieve that string to my android application ,but when i try to invoke the servlet it force close on me
and i dont know why (im very new to android and this is a practice exercise for me)
here is my android simple app:
ANDROID
package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static String request = "kjo ishte e gjitha";
public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
and here is my simple servlet
SERVLET
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String par1 = request.getParameter("param1");
PrintWriter out = response.getWriter();
out.println(par1);
}
}
And the logcat log error says
01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187): at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187): ... 4 more
doest somebody have any idea ?
Thank you for your help in advance !
Have a nice day!
You need to add the internet access permission
<uses-permission android:name="android.permission.INTERNET"/>
I found that you should use the URLEncoder to encode the url because your url contains spaces. Please check http://developer.android.com/reference/java/net/URLEncoder.html
You have forgot to set param1 from your android app.
connection.setRequestProperty("param1", "Your String Value");
then you will get the value back as response from Servlet.

Google Drive SDK Error

This is my code to access Google Drive, taken largely from ArtOfWarfare in this post:
public class MainActivity extends Activity {
class OnTokenAcquired implements AccountManagerCallback<Bundle> {
boolean alreadyTriedAgain;
public OnTokenAcquired() {
// TODO Auto-generated constructor stub
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 3025) {
switch (resultCode) {
case RESULT_OK:
AccountManager am = AccountManager.get(getApplicationContext());
am.getAuthToken(am.getAccounts()[0],
"ouath2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
break;
case RESULT_CANCELED:
// This probably means the user refused to log in. Explain to them why they need to log in.
break;
default:
// This isn't expected... maybe just log whatever code was returned.
break;
}
} else {
// Your application has other intents that it fires off besides the one for Drive's log in if it ever reaches this spot. Handle it here however you'd like.
}
}
#Override
public void run(AccountManagerFuture<Bundle> result) {
try {
final String token = result.getResult().getString(AccountManager.KEY_AUTHTOKEN);
HttpTransport httpTransport = new NetHttpTransport();
JacksonFactory jsonFactory = new JacksonFactory();
Drive.Builder b = new Drive.Builder(httpTransport, jsonFactory, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setKey("my number here");
driveRequest.setOauthToken(token);
}
});
final Drive drive = b.build();
final com.google.api.services.drive.model.File body = new com.google.api.services.drive.model.File();
body.setTitle("My Test File");
body.setDescription("A Test File");
body.setMimeType("text/plain");
File newFile = new File("this");
final FileContent mediaContent = new FileContent("text/plain", newFile);
new Thread(new Runnable() {
public void run() {
try {
com.google.api.services.drive.model.File file = drive.files().insert(body, mediaContent).execute();
alreadyTriedAgain = false; // Global boolean to make sure you don't repeatedly try too many times when the server is down or your code is faulty... they'll block requests until the next day if you make 10 bad requests, I found.
} catch (IOException e) {
if (!alreadyTriedAgain) {
alreadyTriedAgain = true;
AccountManager am = AccountManager.get(getApplicationContext());
am.invalidateAuthToken(am.getAccounts()[0].type, null); // Requires the permissions MANAGE_ACCOUNTS & USE_CREDENTIALS in the Manifest
am.getAuthToken(am.getAccounts()[0],
"ouath2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
} else {
// Give up. Crash or log an error or whatever you want.
}
}
}
}).start();
Intent launch = (Intent)result.getResult().get(AccountManager.KEY_INTENT);
if (launch != null) {
startActivityForResult(launch, 3025);
return; // Not sure why... I wrote it here for some reason. Might not actually be necessary.
}
} catch (OperationCanceledException e) {
// Handle it...
} catch (AuthenticatorException e) {
// Handle it...
} catch (IOException e) {
// Handle it...
}
}
}
private java.io.File downloadGFileToJFolder(Drive drive, String token, File gFile, java.io.File jFolder) throws IOException {
if (gFile.toURI() != null && gFile.toURI().toString().length() > 0 ) {
if (jFolder == null) {
jFolder = Environment.getExternalStorageDirectory();
jFolder.mkdirs();
}
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(gFile.toURI());
get.setHeader("Authorization", "Bearer " + token);
org.apache.http.HttpResponse response = client.execute(get);
InputStream inputStream = response.getEntity().getContent();
jFolder.mkdirs();
java.io.File jFile = new java.io.File(jFolder.getAbsolutePath() + "/" + gFile.getName()); // getGFileName() is my own method... it just grabs originalFilename if it exists or title if it doesn't.
FileOutputStream fileStream = new FileOutputStream(jFile);
byte buffer[] = new byte[1024];
int length;
while ((length=inputStream.read(buffer))>0) {
fileStream.write(buffer, 0, length);
}
fileStream.close();
inputStream.close();
return jFile;
} catch (IOException e) {
// Handle IOExceptions here...
return null;
}
} else {
// Handle the case where the file on Google Drive has no length here.
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getApplicationContext();
AccountManager am = AccountManager.get(this);
am.getAuthToken(am.getAccounts()[0],
"ouath2:" + DriveScopes.DRIVE,
new Bundle(),
true,
new OnTokenAcquired(),
null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I get the following error when I launch the app (Android System also stops momentarily):
11-26 22:31:03.093: E/AndroidRuntime(4288): FATAL EXCEPTION: main
11-26 22:31:03.093: E/AndroidRuntime(4288): java.lang.RuntimeException: Unable to start activity ComponentInfo{android/android.accounts.GrantCredentialsPermissionActivity}: java.lang.NullPointerException
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2260)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.ActivityThread.access$600(ActivityThread.java:139)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1277)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.os.Handler.dispatchMessage(Handler.java:99)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.os.Looper.loop(Looper.java:156)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.ActivityThread.main(ActivityThread.java:5045)
11-26 22:31:03.093: E/AndroidRuntime(4288): at java.lang.reflect.Method.invokeNative(Native Method)
11-26 22:31:03.093: E/AndroidRuntime(4288): at java.lang.reflect.Method.invoke(Method.java:511)
11-26 22:31:03.093: E/AndroidRuntime(4288): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
11-26 22:31:03.093: E/AndroidRuntime(4288): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
11-26 22:31:03.093: E/AndroidRuntime(4288): at dalvik.system.NativeStart.main(Native Method)
11-26 22:31:03.093: E/AndroidRuntime(4288): Caused by: java.lang.NullPointerException
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.accounts.GrantCredentialsPermissionActivity.onCreate(GrantCredentialsPermissionActivity.java:84)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.Activity.performCreate(Activity.java:4543)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)
11-26 22:31:03.093: E/AndroidRuntime(4288): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)
11-26 22:31:03.093: E/AndroidRuntime(4288): ... 11 more
In addition, my phone shows a strange notification: "Permission Requested for account Weather". Anyone have any idea what's causing this?
Try replacing this:
am.getAccounts()[0],
with this:
am.getAccountsByType("com.google")[0],
My code in the other topic was over simplified to assume that the first account it found would be a Google Account (and so have a Google Drive). The code we actually used in the app checked to make sure it was a Google Account (and then performed further checks to make sure it was a company account, which is why I simplified the code to what I shared.)

Categories

Resources