Google Drive SDK Error - java

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.)

Related

Android unable to add getByName

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;
}

How to upload audio in soundcloud via my app and i want to send that id also to my server

I fetching audio from soundcloud and i can stream that audio in my app also,Now the things is how to upload audio to soundcloud and then i want to send the id to my server side also.
My requirement is using the upload button i want to get the file from external storage directory and then i want to send the upload audio.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new GinfyDbAdapter(this);
setContentView(R.layout.upload_audiogallery);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
upload = (ImageButton) findViewById(R.id.btnupload);
btnstop = (Button) findViewById(R.id.btnstop);
//Bundle extras = getIntent().getExtras();
token = (Token) this.getIntent().getSerializableExtra("token");
wrapper = new ApiWrapper("3b70c135a3024d709e97af6b0b686ff3",
"51ec6f9c19487160b5942ccd4f642053",
null,
token);
//for speech to text and recording purpose
setButtonHandlers();
enableButtons(false);
mp = new MediaPlayer();
upload .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//String rootpath = Environment.getExternalStorageDirectory().getAbsolutePath();
//loadAllAudios(rootpath);
File file = new File("/mnt/sdcard/Download/57FYsUnoWxj2.128.mp3");
String path = file.getAbsolutePath();
new MyAsyncTask().execute(path);
UploadToSoundCloudTask uploadTask = new UploadToSoundCloudTask(this, wrapper);
uploadTask.execute(new AudioClip(path));
}
});
}
private class UploadToSoundCloudTask extends AsyncTask<AudioClip, Integer, Integer> {
private Uploadaudiogallery recordActivity;
private ApiWrapper wrapper;
private String clipName;
public UploadToSoundCloudTask(OnClickListener onClickListener, ApiWrapper wrapper) {
this.recordActivity = (Uploadaudiogallery) onClickListener;
this.wrapper = wrapper;
}
#SuppressLint("NewApi")
protected Integer doInBackground(AudioClip... clips) {
try {
Log.d("DDDDD", "uploading in background...");
File audioFile = new File(clips[0].path);
audioFile.setReadable(true, false);
HttpResponse resp = wrapper.post(Request.to(Endpoints.TRACKS)
.add(Params.Track.TAG_LIST, "demo upload")
.withFile(Params.Track.ASSET_DATA, audioFile));
Log.d("DDDDD", "background thread done...");
return Integer.valueOf(resp.getStatusLine().getStatusCode());
} catch (IOException exp) {
Log.d("DDDDD",
"Error uploading audioclip: IOException: "
+ exp.toString());
return Integer.valueOf(500);
}
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Integer result) {
Log.d("DDDDD", "UI thread resume: got result...");
if (result.intValue() == HttpStatus.SC_CREATED) {
Toast.makeText(
this.recordActivity,
"upload successful: "
+ ": " + clipName, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
this.recordActivity,
"Invalid status received: " + result.toString()
+ ": " + clipName, Toast.LENGTH_SHORT).show();
}
}
}
I used Java api-wrapper jar file also.while click upload its shows applicaiton has stopped
Logcat error
10-25 10:35:27.203: E/AndroidRuntime(1921): FATAL EXCEPTION: main
10-25 10:35:27.203: E/AndroidRuntime(1921): java.lang.ClassCastException: com.ibetter.Ginfy.Uploadaudiogallery$4 cannot be cast to com.ibetter.Ginfy.Uploadaudiogallery
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.ibetter.Ginfy.Uploadaudiogallery$UploadToSoundCloudTask.<init>(Uploadaudiogallery.java:85)
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.ibetter.Ginfy.Uploadaudiogallery$4.onClick(Uploadaudiogallery.java:192)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.view.View.performClick(View.java:4204)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.view.View$PerformClick.run(View.java:17355)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.os.Handler.handleCallback(Handler.java:725)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.os.Handler.dispatchMessage(Handler.java:92)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.os.Looper.loop(Looper.java:137)
10-25 10:35:27.203: E/AndroidRuntime(1921): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-25 10:35:27.203: E/AndroidRuntime(1921): at java.lang.reflect.Method.invokeNative(Native Method)
10-25 10:35:27.203: E/AndroidRuntime(1921): at java.lang.reflect.Method.invoke(Method.java:511)
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-25 10:35:27.203: E/AndroidRuntime(1921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-25 10:35:27.203: E/AndroidRuntime(1921): at dalvik.system.NativeStart.main(Native Method)
How can i get the path and uplaod audio to soundcloud and then send id to my server side..
Replace this
UploadToSoundCloudTask uploadTask = new UploadToSoundCloudTask(this, wrapper); uploadTask.execute(new AudioClip(path));
By
UploadToSoundCloudTask uploadTask = new UploadToSoundCloudTask(ActivtiyName.this, wrapper); uploadTask.execute(new AudioClip(path));
In your case this does nto refer to activity context
To upload check the sample here
https://github.com/soundcloud/java-api-wrapper/blob/master/src/examples/java/com/soundcloud/api/examples/UploadFile.java
Downalod java-wrapper-api.jar and add it to libs folder
Get the path of the audio file from sdcard
To uplaod
http://developers.soundcloud.com/docs#uploading
Quoting from the above link
To upload a sound, send a POST request to the /tracks endpoint
Create a wrapper instance:
ApiWrapper wrapper = new ApiWrapper("client_id", "client_secret", null, null);
Obtain a token:
wrapper.login("username", "password");
Make a POST request to the /tracks endpoint. On Button click invoke AsyncTask
class TheTask extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
wrapper = new ApiWrapper("client_id",
"client_secret",
null,
null);
token = wrapper.login("username", "password");
upload();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Upload method.
public void upload()
{
try {
Log.d("DDDDD", "uploading in background...");
File audioFile = new File("/mnt/sdcard/Music/A1.mp3");
// replace the hardcoded path with the path of your audio file
audioFile.setReadable(true, false);
HttpResponse resp = wrapper.post(Request.to(Endpoints.TRACKS)
.add(Params.Track.TITLE, "A1.mp3")
.add(Params.Track.TAG_LIST, "demo upload")
.withFile(Params.Track.ASSET_DATA, audioFile));
Log.i("......",""+Integer.valueOf(resp.getStatusLine().getStatusCode()));
Log.d("DDDDD", "background thread done...");
} catch (IOException exp) {
Log.d("DDDDD",
"Error uploading audioclip: IOException: "
+ exp.toString());
}
}

Programmatically pair Bluetooth device without the user entering pin

The Bluetooth device I am trying to connect has always the same pincode. This should make it possible to pair the device by setting the pin programmatically.
After trying to search how this could be done, I ended up with the code below:
BluetoothDevice device = getDevice();
//To avoid the popup notification:
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device, true);
byte[] pin = ByteBuffer.allocate(4).putInt(1234).array();
//int pinn = 1234;
//Entering pin programmatically:
Method ms = device.getClass().getMethod("setPin", byte[].class);
//Method ms = device.getClass().getMethod("setPasskey", int.class);
ms.invoke(device, pin);
//Bonding the device:
Method mm = device.getClass().getMethod("createBond", (Class[]) null);
mm.invoke(device, (Object[]) null);
cancelPairingUserInput gives me a NoSuchMethodException, which is weird because the method does exist in BluetoothDevice class.
Is looks like Setpin or SetPasskey doesn't do anything. The device just wont pair. It only pairs after manually entering the pin.
So the only line of code that works is:
//Bonding the device:
Method mm = device.getClass().getMethod("createBond", (Class[]) null);
mm.invoke(device, (Object[]) null);
Logcat output:
09-27 12:34:46.408: ERROR/App(11671): cancelPairingUserInput [boolean]
java.lang.NoSuchMethodException: cancelPairingUserInput [boolean]
at java.lang.Class.getConstructorOrMethod(Class.java:460)
at java.lang.Class.getMethod(Class.java:915)
at test.app.bluetooth.model.BluetoothDiscoveryAndPairing.pair(BluetoothDiscoveryAndPairing.java:97)
at test.app.bluetooth.model.BluetoothDiscoveryAndPairing.access$000(BluetoothDiscoveryAndPairing.java:25)
at test.app.bluetooth.model.BluetoothDiscoveryAndPairing$1.onReceive(BluetoothDiscoveryAndPairing.java:79)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:756)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4921)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
So what am I doing wrong?
The hidden method cancelPairingUserInput does not exist in your device. Don't use it.
You should register BroadcastReceiver for android.bluetooth.device.action.PAIRING_REQUEST
Call createBond()
Wait for BroadcastReceiver to trigger
In BroadcastReceiver if action is android.bluetooth.device.action.PAIRING_REQUEST
call this method
public void setBluetoothPairingPin(BluetoothDevice device)
{
byte[] pinBytes = convertPinToBytes("0000");
try {
Log.d(TAG, "Try to set the PIN");
Method m = device.getClass().getMethod("setPin", byte[].class);
m.invoke(device, pinBytes);
Log.d(TAG, "Success to add the PIN.");
try {
device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
Log.d(TAG, "Success to setPairingConfirmation.");
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
e.printStackTrace();
}
}
It also works on a device with Jelly Bean version (4.1.2) of Android.
this is works for me:
IntentFilter filter2 = new IntentFilter(
"android.bluetooth.device.action.PAIRING_REQUEST");
mActivity.registerReceiver(
pairingRequest, filter2);
private final BroadcastReceiver pairingRequest = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
mBluetoothDevice = needed;
try {
byte[] pin = (byte[]) BluetoothDevice.class.getMethod("convertPinToBytes", String.class).invoke(BluetoothDevice.class, "1234");
Method m = mBluetoothDevice.getClass().getMethod("setPin", byte[].class);
m.invoke(mBluetoothDevice, pin);
mBluetoothDevice.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(mBluetoothDevice, true);
}
catch(Exception e)
{
e.printStackTrace();
}

How to handle with no Internet and lost connection in Android?

I have an application that needs to connect to the Internet to perform some actions but when no Internet available it will crash. I read that I need to use try catch bracket in case no Internet. I tried to use it as you can see in AsyncTask but it doesn't work. I don't know why. The app crashes. How to deal with try catch where to put it in my code?
One more thing what about if the app lost Internet connection while process is going on. How supposed I to deal with this thing so my app doesn't crash. Thank you very much.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
lv = (ListView) findViewById(R.id.mybookslistview);
new connectToServer().execute();
}
class connectToServer extends AsyncTask<Void, Void, Void>{
CustomListViewAdapter adapter;
HttpResponse response;
#Override
protected Void doInBackground(Void... params) {
ids_list.clear();
names_list.clear();
writers_list.clear();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair(word, connectionPurpose));
try {
post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
response = client.execute(post);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
sb = new StringBuffer();
String tempVar = "";
while((tempVar = br.readLine()) != null){
sb.append(tempVar);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//Get data from stringbuffer and put it in array list
if(!sb.toString().trim().contentEquals("null")){
content_array = sb.toString().split(",");
for(int s = 0; s < content_array.length; s++){
if(content_array[s].contains("-")){
String temp[] = content_array[s].split("-");
ids_list.add(temp[0].trim());
names_list.add(temp[1].trim());
writers_list.add(temp[2].trim());
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(!mWifi.isConnected()){
adb = new AlertDialog.Builder(Home.this);
adb.setMessage("لا يوجد إنترنت. قم بتفعيل الإنترنت ثم حاول مرة أخرى.");
adb.setPositiveButton("حاول مجددا", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
new connectToServer().execute();
}
});
adb.setNegativeButton("إغلاق التطبيق", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
//It shows dialog if no connection
adb.create().show();
}else{
list = new ArrayList<Home.ListViewItem>();
for(x = 0; x < ids_list.size(); x++){
list.add(new ListViewItem(){{bookName = names_list.get(x); writerName = writers_list.get(x);}});
}
adapter = new CustomListViewAdapter(Home.this, list);
lv.setAdapter(adapter);
if(sb.toString().trim().contentEquals("null")){
Toast.makeText(Home.this, "لا توجد نتائج.", Toast.LENGTH_LONG).show();
}
}
This is my logcat:
java.net.UnknownHostException: Unable to resolve host "globalmall.ca": No address associated with hostname
at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
at readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.getaddrinfo(Native Method)
at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:55)
at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
... 18 more
Caused by: libcore.io.ErrnoException: getaddrinfo failed: ENETUNREACH (Network is unreachable)
... 21 more
threadid=13: thread exiting with uncaught exception (group=0x40e582a0)
You can either create method or some class may be where you can instantiate method as static.
Here is a method named isConnectedToInternet() which checks whether internet is connected or not. Return boolean on the basis of connection back to the calling function.
Snippet:
public boolean isConnectedToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
You can decide on the basis of return value of isConnectedToInternet() whether to execute AysncTask or Throw some pop up. Here i've been added user to brought in his Data Settings.
Something like these:
if(isConnectedToInternet())
{
// Run AsyncTask
}
else
{
// Here I've been added intent to open up data settings
Intent intent=new Intent(Settings.ACTION_MAIN);
ComponentName cName = new ComponentName("com.android.phone","com.android.phone.NetworkSetting");
intent.setComponent(cName);
}
As you mentioned what if you looses connection in between. You can check the status code as per the reponse of httpclient and pop up relevant information to user.
You can integrate these snippet under AysncTask.
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpResponse response = null;
response = httpclient.execute(httpget);
int code = response.getStatusLine().getStatusCode();
public class CheckNetClass {
public static Boolean checknetwork(Context mContext) {
NetworkInfo info = ((ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option, you can change it if you want to
// disable internet while roaming, just return false
return true;
}
return true;
}
}
Use this class to check internet availability like:
if (CheckNetClass.checknetwork(getApplicationContext()))
{
new GetCounterTask().execute();
}
else
{
Toast.makeText(getApplicationContext(),"Sorry,no internet connectivty",1).show();
}
Hope this helps..
Interesting. You have in your stack trace these lines:
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
readit.Mansour.inc.Home$connectToServer.doInBackground(Home.java:106)
Which mean that the offending line is
response = client.execute(post);
Which is different from the line that you mentioned. Verify the stack trace & the line that it mentions. Also, see that if you fix it by catching Exception. If you don't, then you have a bigger problem, because UnknownHostException is a subclass of IOException, which you already catch.

Gson and Google

I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Categories

Resources