Failed upload to FTP using simpleFTP - java

I want to upload images to fto using simple FTP. But it always failed to upload to FTP. The error always points to the ftp.connect. I don't know why. So I hope u can help me.
Upload.java
public class ImageUpdate extends AppCompatActivity {
private static final String TAG_ID = "id";
private static final String TAG_PESAN = "message";
private static final String TAG_HASIL = "result";
private static final String TAG_IMAGE_ID = "id_image";
private static final String TAG_IMAGE_NAME= "image_name";
ProgressDialog pDialog;
JSONParser jparser = new JSONParser();
ArrayList<HashMap<String, String>> namelist, idList, imageList;
JSONArray names, names1, names2;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString = null;
Button submit;
static final String FTP_HOST = "xxxxxxxxxx";
static final String FTP_USER = "xxxxxxxxxxxx";
static final String FTP_PASS = "xxxxxxxxxxx";
String name, vid;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client2;
SessionManagement session;
String nm,addr,pos,tlp,mail,usr,pass,id,image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_update);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
session =new SessionManagement(ImageUpdate.this);
HashMap<String, String> user = session.getUserDetails();
id=user.get(SessionManagement.KEY_ID);
nm=user.get(SessionManagement.KEY_NAME);
addr=user.get(SessionManagement.KEY_ALAMAT);
mail=user.get(SessionManagement.KEY_EMAIL);
tlp=user.get(SessionManagement.KEY_TELP);
usr=user.get(SessionManagement.KEY_USERNAME);
pass=user.get(SessionManagement.KEY_PASS);
submit=(Button) findViewById(R.id.buttonUploadPicture);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (imgDecodableString == null) {
Toast.makeText(ImageUpdate.this, "Choose image first, please", Toast.LENGTH_LONG);
} else {
File f = new File(imgDecodableString);
name = f.getName();
uploadFile(f);
}
}
});
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filename = cursor.getString(columnIndex);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
File f = new File("" + imgDecodableString);
f.getName();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "Pilih Bukti Transaksi",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Failed to Choose", Toast.LENGTH_LONG)
.show();
}
}
public void uploadFile(File fileName) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SimpleFTP ftp=new SimpleFTP();
try {
ftp.connect("xxxxxxx", 21, "xxxxxxxx", "xxxxxxx");
ftp.bin();
ftp.cwd("img/imageProfil/");
ftp.stor(fileName);
ftp.disconnect();
} catch (Exception e) {
e.printStackTrace();
try {
ftp.disconnect();
Toast.makeText(ImageUpdate.this, "disconnect", Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(ImageUpdate.this, "failed", Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Upload Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
);
AppIndex.AppIndexApi.start(client2, viewAction);
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Upload Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app deep link URI is correct.
Uri.parse("android-app://com.amobi.newlomapodfix/http/host/path")
);
AppIndex.AppIndexApi.end(client2, viewAction);
client2.disconnect();
}
}
stackTrace
06-20 22:32:00.692 2845-2845/com.amobi.newlomapodfix W/EGL_emulation: eglSurfaceAttrib not implemented
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: java.io.IOException: SimpleFTP received an unknown response when connecting to the FTP server: 220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:74)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at com.amobi.newlomapodfix.UploadActivity.uploadFile(UploadActivity.java:167)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at com.amobi.newlomapodfix.UploadActivity$1.onClick(UploadActivity.java:100)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.view.View.performClick(View.java:4204)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.view.View$PerformClick.run(View.java:17355)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Handler.handleCallback(Handler.java:725)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.os.Looper.loop(Looper.java:137)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5041)
06-20 22:32:04.900 2845-2845/com.amobi.newlomapodfix W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
06-20 22:32:04.904 2845-2845/com.amobi.newlomapodfix W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
06-20 22:32:04.908 2845-2845/com.amobi.newlomapodfix W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-20 22:32:04.912 2845-2845/com.amobi.newlomapodfix W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-20 22:32:04.912 2845-2845/com.amobi.newlomapodfix W/System.err: at dalvik.system.NativeStart.main(Native Method)

This answer explains a nonconform FTP specification in simple FTP, in fact, the server should start with 220 but this library gets an exception.
(https://stackoverflow.com/a/24386510/6093353).
This tutorial implements an easy FTP upload, try to follow this
http://androidexample.com/FTP_File_Upload_From_Sdcard_to_server/index.php?view=article_discription&aid=98

Related

how to continue service when device go to sleep?

I am new to android.I want to use my service for fetching the Json data from server.when I open my app then all works fine but when I exit my app or when my device go to sleep then there is a Json exception.how can I make my service run every-time in background. Please guide for solving this error.
error:-
E/agdghdgdgdrgrdgrdg: dgdgd
W/System.err: java.net.UnknownHostException: Unable to resolve host
"podgier-
woman.000webhostapp.com": No address associated with hostname
W/System.err: at
java.net.InetAddress.lookupHostByName(InetAddress.java:457)
W/System.err: at
java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
W/System.err: at
java.net.InetAddress.getAllByName(InetAddress.java:215)
W/System.err: at
org.apache.http.conn.DefaultClientConnectionOperator.openConnection
(DefaultClientConnectionOperator.java:137)
W/System.err:at org.apache.http.impl.conn.AbstractPoolEntry.open
(AbstractPoolEntry.java:164)
W/Systemerr:at
org.apache.http.impl.conn.AbstractPooledConnAdapter.open
(AbstractPooledConnAdapter.java:119)
W/System.err: at
org.apache.http.impl.client.DefaultRequestDirector.execute
(DefaultRequestDirector.java:360)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:555)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:487)
W/System.err:at
org.apache.http.impl.client.AbstractHttpClient.execute
(AbstractHttpClient.java:465)
W/System.err: at com.grover.jsonp.JSONParser.makeHttpRequest
(JSONParser.java:62)
W/System.err:at com.grover.jsonp.BackgroundService$gro.doInBackground
(BackgroundService.java:50)
W/System.err: at
com.grover.jsonp.BackgroundService$gro.doInBackground
(BackgroundService.java:41)
W/System.err:at android.os.AsyncTask$2.call(AsyncTask.java:288)
W/System.err:at java.util.concurrent.FutureTask.run
(FutureTask.java:237)
W/System.err: at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker
(ThreadPoolExecutor.java:1112)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor
$Worker.run(ThreadPoolExecutor.java:587)
W/System.err: at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: android.system.GaiException:
android_getaddrinfo
failed: EAI_NODATA (No address associated with hostname)
W/System.err: at libcore.io.Posix.android_getaddrinfo(Native
Method)
W/System.err: at
libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
W/System.err: at
java.net.InetAddress.lookupHostByName(InetAddress.java:438)
W/System.err: ... 18 more
E/Buffer Error: Error converting result java.io.IOException: Attempted
read
on closed stream.
BackgroundService.java
public class BackgroundService extends Service
{
public BackgroundService(){
}
private static String url ="https://podgier-woman.000webhostapp.com/table.php";
JSONParser jParser = new JSONParser();
ArrayList<String> bcv;
class gro extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(String... args) {
java.util.List<NameValuePair> pr = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url, "GET", pr);
bcv = new ArrayList<String>();
try {
JSONArray code = json.getJSONArray("code");
Log.d("list :",code.toString());
for (int i = 0; i < code.length(); i++) {
JSONObject c = code.getJSONObject(i);
bcv.add(c.getString("name"));
// adding each child node to HashMap key => value
// adding contact to contact list
JSONArray p = null;
}
}catch(JSONException e){
}
return null;
}
protected void onPostExecute(String file_url) {
Log.v("sdg","sgfdg"+record.idName);
if(record.idName < bcv.size()){
int xx= bcv.size() - record.idName;
Intent intent = new Intent(BackgroundService.this, record.class);
PendingIntent pIntent = PendingIntent.getActivity(BackgroundService.this, (int) System.currentTimeMillis(),intent, 0);
Log.d("SGsgzxv","dfgzdvv");
Notification n = new Notification.Builder(getApplicationContext())
.setContentTitle("View "+xx+" updated data")
.setContentText("data pending ")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.mipmap.ic_launcher, "call", pIntent)
.addAction(R.mipmap.ic_launcher, "More", pIntent)
.addAction(R.mipmap.ic_launcher, "and more", pIntent)
.build();
Uri so = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
n.sound = so;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(0,n);
}
record.idName = bcv.size();
bcv.clear();
}
}
private static final String TAG = "BackgroundService";
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");
#Override
public void onCreate() {
super.onCreate();
Log.v(TAG, "in onCreate()");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
int counter = intent.getExtras().getInt("counter");
Log.v(TAG, "in onStartCommand(), counter = " + counter +
", startId = " + startId);
new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
.start();
return START_STICKY;
}
class ServiceWorker implements Runnable
{
private int counter = -1;
public ServiceWorker(int counter) {
this.counter = counter;
}
public void run() {
final String TAG2 = "ServiceWorker:" + Thread.currentThread().getId();
// do background processing here...
try {
Log.e(TAG2, "sleeping for 5 seconds. counter = " + counter);
while(true)
{
Thread.sleep(9000);
Log.e("agdghdgdgdrgrdgrdg","dgdgd");
new gro().execute();
}
} catch (InterruptedException e) {
Log.e(TAG2, "... sleep interrupted");
}
}
}
#Override
public void onDestroy()
{
}
#Override
public IBinder onBind(Intent intent) {
Log.v(TAG, "in onBind()");
return null;
}
}
I don't recommend using a background service for such purposes. I know from experience that we are never sure that such a service will not be destroyed by the system.
To perform tasks (periodic, single) I recommend using Firebase Job Dispatcher. In my opinion, this is a more reliable mechanism when it comes to doing background work.
Here is an example of use, given by me: https://stackoverflow.com/a/44489327/8119117

Capture Image, Upload To Firebase And Retrieve Java Android Studio

I am very sorry if this may be a question with a simple solution.
What Am I Trying To Do?
Capture an image from a Button
Upload that image to Firebase storage
Retrieve that image in an ImageView
What Is My Trouble So Far?
Takes picture, but crashes when I click the tick.
Hence nothing is being uploaded or being achieved.
My Code
P.N I have looked at lots of other forums and video tutorials but nothing seems to be working. Hopefully someone can help.
public class LeaderboardActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST_CODE = 1;
private static final int REQUEST_TAKE_PHOTO = 1;
private StorageReference mStorage;
private ProgressDialog mProgress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
mStorage = FirebaseStorage.getInstance().getReference();
final Button bImage = (Button) findViewById(R.id.bCamera);
final ImageView ivPic = (ImageView) findViewById(R.id.ivPic);
mProgress = new ProgressDialog(this);
bImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgress.setMessage("Uploading Image");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photo").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Toast.makeText(LeaderboardActivity.this, "Uploading Complete...", Toast.LENGTH_LONG);
}
});
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
Error In Android Monitor
Not sure if this will help
02-13 02:30:32.693 2133-2133/com.example.rikhi.chores E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rikhi.chores, PID: 2133
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.rikhi.chores/com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity.onActivityResult(LeaderboardActivity.java:74)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132) 
at android.app.ActivityThread.-wrap20(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
I have looked at other people who had the same problem, followed what they said nothing happend, followed the Google Android instructions for this and again same problem.
On button, click remove that intent and just call your
dispatchTakePictureIntetnt() method on Onclick button Listener
Also, check go to your emulator settings, and check your camera
permission is on for your this app and also go to firebase console
and check the rules if, rules are not equal to null made them equal
to null then run your app because !=null rules only work when there
is an authentication method in your app

Displaying image taken by camera API android

I have been following this tutorial: AndroidHive - working with Camera API to try and enable taking photos in my app. However, I'm getting an error once I press my "take photo button".
LogCat:
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/Dob_in_a_Hoon_photos﹕ Failed to create Dob_in_a_Hoon_photos directory
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour D/AndroidRuntime﹕ Shutting down VM
09-16 11:04:00.539 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40e21438)
09-16 11:04:00.559 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: file
at android.net.Uri.fromFile(Uri.java:441)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.getOutputMediaFileUri(dob_in_a_hoon.java:97)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.captureImage(dob_in_a_hoon.java:89)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon.access$000(dob_in_a_hoon.java:28)
at au.gov.nsw.shellharbour.saferroadsshellharbour.dob_in_a_hoon$1.onClick(dob_in_a_hoon.java:60)
at android.view.View.performClick(View.java:4191)
at android.view.View$PerformClick.run(View.java:17229)
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:4963)
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)
09-16 11:04:10.529 19561-19561/au.gov.nsw.shellharbour.saferroadsshellharbour I/Process﹕ Sending signal. PID: 19561 SIG: 9
Here is my .java file:
public class dob_in_a_hoon extends ActionBarActivity {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Dob_in_a_Hoon_photos";
private Uri fileUri;
private ImageView Hoon_Image;
private Button button_take_photo;
private String driver_spinner_array[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dob_in_a_hoon);
driver_spinner_array = new String[2];
driver_spinner_array[0] = "Yes";
driver_spinner_array[1] = "No";
Spinner Driver_spinner = (Spinner) findViewById(R.id.driver_selector);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_dropdown_item_1line, driver_spinner_array);
Driver_spinner.setAdapter(adapter);
Hoon_Image = (ImageView) findViewById(R.id.CapturedImage);
button_take_photo = (Button)findViewById(R.id.btn_take_photo);
button_take_photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.dob_in_a_hoon, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void captureImage(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),IMAGE_DIRECTORY_NAME);
if (!mediaStorageDir.exists()){
if (!mediaStorageDir.mkdirs()){
Log.d(IMAGE_DIRECTORY_NAME, "Failed to create " + IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
if (type==MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");
}else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE){
if (resultCode==RESULT_OK){
previewCapturedImage();
}else if (resultCode == RESULT_CANCELED){
Toast.makeText(getApplicationContext(),"User Cancelled image Capture", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(),"Failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
private void previewCapturedImage(){
try{
Hoon_Image.setVisibility(View.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);
Hoon_Image.setImageBitmap(bitmap);
}catch (NullPointerException e){
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState){
super .onSaveInstanceState(outState);
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
fileUri = savedInstanceState.getParcelable("file_uri");
}
}
Can anybody see where I am going wrong in my code, and what I have to do to fix it?
I created a sample snippet and tested out the mkdirs as shown in your code, it causes similar exception if i removed the permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Can you please check your manifest to make sure you have these defined.
If above is not the problem, another (unlikely) source of error could be your SD card is running out of space or some permissions restrictions. In this case, i would try the app on android emulator or another device.
This should be added in Manifest to use camera feature:
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:glEsVersion="0x00020000"
android:required="true"/>

MY android application is crashing when I click on the register btn

While running my application I go to click on the register button and the application is crashing. Please find Log-cat below (if anyone could explain the best way to use log-cat that would be great) I have also included the register Java. If there is any more information you need comment and I will update this message.
04-23 21:52:07.835: D/libEGL(28588): loaded /system/lib/egl/libEGL_mali.so
04-23 21:52:07.875: D/libEGL(28588): loaded /system/lib/egl/libGLESv1_CM_mali.so
04-23 21:52:07.885: D/libEGL(28588): loaded /system/lib/egl/libGLESv2_mali.so
04-23 21:52:07.895: E/(28588): Device driver API match
04-23 21:52:07.895: E/(28588): Device driver API version: 23
04-23 21:52:07.895: E/(28588): User space API version: 23
04-23 21:52:07.895: E/(28588): mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Wed Oct 9 21:05:57 KST 2013
04-23 21:52:08.000: D/OpenGLRenderer(28588): Enabling debug mode 0
04-23 21:52:24.925: D/AndroidRuntime(28588): Shutting down VM
04-23 21:52:24.925: W/dalvikvm(28588): threadid=1: thread exiting with uncaught exception (group=0x41ba8700)
04-23 21:52:24.930: E/AndroidRuntime(28588): FATAL EXCEPTION: main
04-23 21:52:24.930: E/AndroidRuntime(28588): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loggedin/com.loggedin.Register}: java.lang.NullPointerException
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.access$700(ActivityThread.java:159)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.os.Handler.dispatchMessage(Handler.java:99)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.os.Looper.loop(Looper.java:176)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.main(ActivityThread.java:5419)
04-23 21:52:24.930: E/AndroidRuntime(28588): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 21:52:24.930: E/AndroidRuntime(28588): at java.lang.reflect.Method.invoke(Method.java:525)
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
04-23 21:52:24.930: E/AndroidRuntime(28588): at dalvik.system.NativeStart.main(Native Method)
04-23 21:52:24.930: E/AndroidRuntime(28588): Caused by: java.lang.NullPointerException
04-23 21:52:24.930: E/AndroidRuntime(28588): at com.loggedin.Register.onCreate(Register.java:83)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.Activity.performCreate(Activity.java:5372)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
04-23 21:52:24.930: E/AndroidRuntime(28588): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257)
the following code is the Register page
package com.loggedin;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.loggedin.internal.DatabaseHandler;
import com.loggedin.internal.UserFunctions;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "id";
private static String KEY_FIRSTNAME = "FirstName";
private static String KEY_LASTNAME = "LastName";
private static String KEY_USERNAME = "Username";
private static String KEY_EMAIL = "email";
private static String KEY_DOB = "DOB";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputDOB;
EditText inputPassword;
Button btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.FirstName);
inputLastName = (EditText) findViewById(R.id.LastName);
inputUsername = (EditText) findViewById(R.id.Username);
inputEmail = (EditText) findViewById(R.id.email);
inputDOB = (EditText) findViewById(R.id.DOB);
inputPassword = (EditText) findViewById(R.id.Password);
btnRegister = (Button) findViewById(R.id.registerbtn1);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Button which Switches back to the login screen on clicked
**/
Button login = (Button) findViewById(R.id.bktologinbtn);
login.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Login.class);
startActivityForResult(myIntent, 0);
finish();
}
});
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputDOB.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
InternetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class InternetCheck extends AsyncTask<String, Boolean, Boolean> {
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask <String, String, JSONObject>{
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,Password,FirstName,LastName,DOB,Username;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.Username);
inputPassword = (EditText) findViewById(R.id.Password);
FirstName = inputFirstName.getText().toString();
LastName = inputLastName.getText().toString();
email = inputEmail.getText().toString();
DOB = inputDOB.getText().toString();
Username= inputUsername.getText().toString();
Password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(FirstName, LastName, DOB, email, Username, Password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(),Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void InternetAsync(View view){
new InternetCheck().execute();
}
}
Some advice when using logcat...
E/AndroidRuntime(28588): Caused by: java.lang.NullPointerException
E/AndroidRuntime(28588): at
com.loggedin.Register.onCreate(Register.java:83)
You can always do a quick text search checking out the caused By: you can find out where you went wrong.Logcat also shows where the error was thrown too in your case line #83.
I'd recommend looking into how to use the debugger properly too, it is pretty important:
http://forum.xda-developers.com/showthread.php?t=1726238
http://www.vogella.com/tutorials/AndroidLogging/article.html
As Mike already said, debugger can really help you find the issue.
In this case, the line is:
btnRegister.setOnClickListener(new View.OnClickListener() {
The problem is when you use findViewById:
public View findViewById (int id)
Added in API level 1
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
Returns
The view if found or null otherwise.
This means that findViewById returns a null pointer :) so, check your id in the XML layout.
The error is obvious and ppl correctly said regarding using debugger and logcat..
Anyways following are my views :-
1. plz cross check your xml file activity_register.xml dat it has the id which you are using here.
since the error is happening in onclick of the button and then try to capture everything inside onlick in exception using try - catch also surrond the whole button click inside try-catch . add two Toast with different msgs as to identify where the exception is raised.
also u can simply add Log msg like this Log.e("IS_REGISTER_BUTTON_NULL","Value : " +btnRegister) in on create after getting the id if its not null it will write some character other then null. also remove everything inside the onlick and see for each string values u r taking like
String uName=inputUsername.getText().toString();
String pWd=inputPassword.getText().toString();
.
.
.
Log.e("CHECKING_IF_STRING_ARE_NULL",uName+" "+pWd+" "+eMail+.....);
thx

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

Categories

Resources