Android displaying image from Database - java

Hi I learned how to grab data from a SQL and display onto TextView. But I'm having little trouble displaying images.
The images are stored in the SQL database as URL but I can't display as an image onto the view.
I've done some research and found on "How to display image with given URL", but I'm just having a little difficulty understanding the concept of grabbing the URL and display .. Please kindly help me. Thank you!
This is the errorLog i'm getting.
Update
Line 159 : photoMe.setImageDrawable(drawable);
11-15 14:53:21.450: W/LoadImageFromWebOperations(28444): java.net.MalformedURLException: Protocol not found: photo
11-15 14:53:21.480: D/AndroidRuntime(28444): Shutting down VM
11-15 14:53:21.480: W/dalvikvm(28444): threadid=1: thread exiting with uncaught exception (group=0x40c55a68)
11-15 14:53:21.500: E/AndroidRuntime(28444): FATAL EXCEPTION: main
11-15 14:53:21.500: E/AndroidRuntime(28444): java.lang.NullPointerException
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.app.android.DirectoryDetailMeActivity$GetDirectoryDetails$1.run(DirectoryDetailMeActivity.java:159)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.handleCallback(Handler.java:605)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Looper.loop(Looper.java:137)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.app.ActivityThread.main(ActivityThread.java:4517)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invoke(Method.java:511)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-15 14:53:21.500: E/AndroidRuntime(28444): at dalvik.system.NativeStart.main(Native Method)
public class DirectoryDetailMeActivity extends Activity {
ImageView photoMe;
TextView txtName;
String uid;
String photo = "";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_veiw_directory = "directory_detail_me.php";
private static final String TAG_ID = "uid";
private static final String TAG_IMG = "photo";
private static final String TAG_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory_detail_me);
uid = i.getStringExtra(TAG_ID);
new GetDirectoryDetails().execute();
}
class GetDirectoryDetails extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", uid));
JSONObject json = jsonParser.makeHttpRequest(url_veiw_directory, "GET", params);
Log.d("my profile", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray directoryObj = json.getJSONArray(TAG_DIRECTORY);
JSONObject directory = directoryObj.getJSONObject(0);
txtName.setText(directory.getString(TAG_NAME));
Drawable drawable = LoadImageURL(TAG_IMG);
photoMe.setImageDrawable(drawable);
txtName = (TextView) findViewById(R.id.name);
photoMe = (ImageView) findViewById(R.id.photo);
}else{
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private Drawable LoadImageURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "photo");
return d;
}
catch (Exception e)
{
Log.w("LoadImageURL",e.toString());
return null;
}
}
});
return null;
}
}
}

You don't seem to understand an AsyncTask. The point is that it does not run on the UI thread, making it possible to do long term IO like HTTP connections. Wrapping the entire doInBackground in a runOnUIThread is completely counter to that. Its not your only problem, but its on the list.
The rest is too hard to read due to formatting, but look on line 159. Some variable you're using there is null.

Related

Android - Error when uploading multiple images

I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
return responseString;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).

Writing a TableRow on UI thread with data from AsyncTask Thread

I have implemented a JSON Parser on a background thread and then am trying to write the data to a series of TableRows on the UI Thread using some embedded code which includes a handler to put me back on the normal UI Thread. The code continually comes back with this stack trace
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6123
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:244)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
04-21 14:58:08.506 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
04-21 14:58:11.316 6199-6215/webmd.mmu.ac.uk.wmfinal3 D/dalvikvm﹕ GC_FOR_ALLOC freed 209K, 10% free 3129K/3460K, paused 2ms, total 2ms
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/AndroidRuntime﹕ Shutting down VM
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cb3b20)
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6199
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:245)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I tried moving all the code into the AsyncTask but it then demands to be on the UI Thread.
Here is my code. Any help would be much appreciated.
protected Boolean doInBackground(final String... args) {
final TableLayout tl = (TableLayout) findViewById(R.id.table);
final TableRow v1 = new TableRow(MainActivity.this);
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
int [] test = new int [10];
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
//testing(vbn,va1,va2,va3,vpost,vratestar);
//TableLayout tl = (TableLayout) findViewById(R.id.table);
isRunning = true;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tl.addView(v1);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
isRunning = false;
//jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
UPDATE: Now shows v1 initialization
Looking at your while (isRunning) loop I suppose you are trying to add the same v1 TableRow view to the TableLayout on each iteration (however, it is just a guess, because you didn't post v1 declaration). Of course, at the second time it will give you an error as it is already has parent, you should create new TableRow object each time. Going deeper, you don't need Handler which is connected to UI thread, because you are using AsyncTask, you can take advantage of the fact, that onPostExecute method is executed on the main thread. Considering it, you can write the following AsyncTask implementation:
class MyAsyncTask extends AsyncTask<Void, Void, JSONArray>{
#Override
protected JSONArray doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
TableLayout tl = (TableLayout) findViewById(R.id.table);
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
TableRow tableRow = new TableRow(context);
//configuring row, setting layout params
tl.addView(tableRow);
} catch (JSONException ex){
//error handling
}
}
}
}

URL cannot be cast to String

I am very new in android and trying to develop application to load all mp3 files from server to list-view and by clicking list item it should play that mp3 file directly from server.
Somehow i am able to list all mp3 files from server to list-view but when i click on list-view's item to play that particular song it giving me following error.
Logcat
02-18 11:49:58.266: E/AndroidRuntime(8276): FATAL EXCEPTION: main
02-18 11:49:58.266: E/AndroidRuntime(8276): java.lang.ClassCastException: java.net.URL cannot be cast to java.lang.String
02-18 11:49:58.266: E/AndroidRuntime(8276): at iqual.fidol_final.ServerFileList$1.onItemClick(ServerFileList.java:72)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AdapterView.performItemClick(AdapterView.java:295)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AbsListView.performItemClick(AbsListView.java:1073)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2577)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.widget.AbsListView$1.run(AbsListView.java:3302)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.os.Handler.handleCallback(Handler.java:605)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.os.Handler.dispatchMessage(Handler.java:92)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.os.Looper.loop(Looper.java:154)
02-18 11:49:58.266: E/AndroidRuntime(8276): at android.app.ActivityThread.main(ActivityThread.java:4624)
02-18 11:49:58.266: E/AndroidRuntime(8276): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 11:49:58.266: E/AndroidRuntime(8276): at java.lang.reflect.Method.invoke(Method.java:511)
02-18 11:49:58.266: E/AndroidRuntime(8276): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
02-18 11:49:58.266: E/AndroidRuntime(8276): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
02-18 11:49:58.266: E/AndroidRuntime(8276): at dalvik.system.NativeStart.main(Native Method)
Java Code
public class ServerFileList extends Activity implements
OnBufferingUpdateListener, OnErrorListener, OnPreparedListener {
Uri uri;
URL urlAudio;
ListView mListView;
PlaySongAsy play;
ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
MediaPlayer mp = new MediaPlayer();
private List<String> myList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.serverfilelist);
mListView = (ListView) findViewById(R.id.listAudio);
if (Const.server == 0) {
new getAudiofromServer().execute();
} else {
new getVideofromServer().execute();
}
// new downloadAudio().execute();
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// playSong(urlAudio + myList.get(position));
play = (PlaySongAsy) new PlaySongAsy(myList.get(position)
.replace(" ", "%20").trim()).execute();
}
});
}
class PlaySongAsy extends AsyncTask<String, Void, Boolean> {
String baseURL;
public PlaySongAsy(String baseURL) {
this.baseURL = baseURL;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = ProgressDialog.show(ServerFileList.this,
" Buffering...", "please wait..", false);
pDialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
new Thread() {
#Override
public void run() {
play(baseURL);
}
}.start();
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// progressDialog.dismiss();
}
}
private void play(String baseURL) {
Uri myUri = Uri.parse(baseURL);
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
// mp.setVolume(5.F, 5.F);
Log.d("", "LoadClip Done");
} catch (Throwable t) {
Log.d("", t.toString());
}
}
public void updateProgress(int currentSize, int totalSize) {
TextView mTextView = new TextView(ServerFileList.this);
mTextView.setText(Long.toString((currentSize / totalSize) * 100) + "%");
}
}
The code:
myList.get(position)
is implicitly casting the element of myList to a String, since myList is a List<String>. This is failing because you managed to insert a URL object into myList.
Enable "unchecked cast" warnings, and you should see a warning where you are inserting into myList.
Two possible fixes:
Eliminate the unchecked cast. Part of that will probably involve calling .toString() on your URL before adding it to myList.
Or, change the type of myList to List<URL>, and then do the .toString() call inside onItemClick.
Which one you go with depends on the type you'd like myList to have.
I think that myList contains wrong objects. You put URIs inside it, not Strings. Use toString method on Uris when you filling list.
Find where you do this:
myList.add((String)uri);
and change to:
myList.add(uri.toString());
Invoke toString() method on the URL object to get the string form.
Refer http://docs.oracle.com/javase/6/docs/api/java/net/URL.html#toString%28%29
Your `Exception saying...
java.lang.ClassCastException: java.net.URL cannot be cast to java.lang.String
Which boldly indicating, you are trying to cast an URL to a String object...that means, baseURL is an URL object but you are trying to cast it to a String object, that's why Exception happening.
Now, Change the following...
String baseURL;
to
Uri baseURL;
As well as, where you are referencing baseURL as a String, change them as Uri.
Try removing all the unnecessary spaces in your URL by calling trim().
Please refer the below question as well
Android: howto parse URL String with spaces to URI object?

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

ImageLoader NullPointerException for an off-screen, SlidingMenu item?

I'm parsing a JSON response from a weather feed and the data I receive includes a url to an icon that corresponds with the conditions, then I display that icon in an ImageView. I was able to make this work in a sandbox app before moving the package of code into my project.
In the main project I use the latest versions of ActionBarSherlock and SlidingMenu for navigation, and both apps make use of Android-Async-Http-Client but now it has a fatal NullPointerException when trying to display the icon from that url in the ImageView. I don't think this is caused by any of the libraries.
I've seen that sliding menus mostly consist of some type of ListView handled with an Adapter, which I'm doing in a portion of my sliding menu. But the only clue I have is that it crashes because now it's an off-screen UI element that I'm trying to work with. Does it matter that I have something in my sliding menu that isn't handled by an Adapter? I can't imagine much else is different but maybe you guys some clue of what I'm missing. Hopefully it isn't something basic that I'm just forgetting... or maybe it is :)
Alright, thanks for any ideas.
public class MainActivity extends SlidingActivity implements
ActionBar.OnNavigationListener {
final String TAG = "MainActivity";
private TextView mSelected;
private String[] mLocations;
ImageLoader imageLoader;
ImageView weatherIcon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageLoader = new ImageLoader(this);
wireViews();
getWeatherFeed();
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(
context, R.array.activities, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// set the Behind View
setBehindContentView(R.layout.menu_frame);
// SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setSlidingActionBarEnabled(false);
ListView menuList = (ListView) findViewById(R.id.menuList);
SlidingMenuItem[] data = new SlidingMenuItem[] {
new SlidingMenuItem("Item1 Label", "Item1 Sub-label",getResources().getDrawable(R.drawable.item1)),
new SlidingMenuItem("Item2 Label", "Item2 Sub-Label",getResources().getDrawable(R.drawable.item2)) };
MenuAdapter adapter = new MenuAdapter(this, R.layout.sliding_menu_item,
data);
menuList.setAdapter(adapter);
}
private void updateWeatherUi(String degreeText, String descriptionText,
String iconUrl) {
Log.i(TAG, "Updating UI elements...");
if (imageLoader != null) {
Log.i(TAG, "IMAGE_LOADER NOT NULL!!!");
}
imageLoader.DisplayImage(iconUrl, weatherIcon); // FIXME: FATAL CRASH HERE !!!
}
/** Build a Weather object from the JSON response.
* #throws JSONException */
private void buildWeatherObject(String rawResponse) throws JSONException {
Log.i(TAG, "Building Weather ojbect...");
JSONObject baseObject = new JSONObject(rawResponse);
JSONObject data = new JSONObject(baseObject.getString(Key.DATA));
JSONArray conditionArray = new JSONArray(
data.getString(Key.CURRENT_CONDITION));
for (int i = 0; i < conditionArray.length(); i++) {
JSONObject conditionElement = new JSONObject(
conditionArray.getString(i));
weather = new Weather();
weather.tempMaxF = conditionElement.getString(Key.TEMP_F);
JSONArray weatherDescriptionArray = new JSONArray(
conditionElement.getString(Key.W_WEATHER_DESC));
for (int j = 0; j < weatherDescriptionArray.length(); j++) {
JSONObject weatherDescriptionElement = new JSONObject(
weatherDescriptionArray.getString(j));
weather.weatherDesc = weatherDescriptionElement
.getString(Key.VALUE);
}
JSONArray weatherIconArray = new JSONArray(
conditionElement.getString(Key.WEATHER_ICON_URL));
for (int j = 0; j < weatherIconArray.length(); j++) {
JSONObject weatherIconElement = new JSONObject(
weatherIconArray.getString(j));
weather.weatherIconUrl = weatherIconElement
.getString(Key.VALUE);
Log.i(TAG, weather.weatherIconUrl);
}
conditionElement = null;
updateWeatherUi(weather.tempMaxF, weather.weatherDesc,
weather.weatherIconUrl);
}
}
/** Asynchronously request and receive weather feed data. */
private void getWeatherFeed() {
Log.i(TAG, "Getting asynchronous JSON feed...");
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_FEED_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
buildWeatherObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0, String arg1) {
super.onFailure(arg0, arg1);
showToast("Sorry, the weather forecast wasn't available just then.");
}
});
}
private void wireViews() {
Log.i(TAG, "Wiring UI elements...");
mSelected = (TextView) findViewById(R.id.text);
mLocations = getResources().getStringArray(R.array.activities);
weatherIcon = (ImageView) findViewById(R.id.weatherIconView);
}
12-21 01:01:11.130: I/MainActivity(28502): Building Weather ojbect...
12-21 01:01:11.170: I/MainActivity(28502): http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png
12-21 01:01:11.170: I/MainActivity(28502): Updating UI elements...
12-21 01:01:11.170: I/MainActivity(28502): IMAGE_LOADER NOT NULL!!!
12-21 01:01:11.170: D/AndroidRuntime(28502): Shutting down VM
12-21 01:01:11.170: W/dalvikvm(28502): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
12-21 01:01:11.180: E/AndroidRuntime(28502): FATAL EXCEPTION: main
12-21 01:01:11.180: E/AndroidRuntime(28502): java.lang.NullPointerException
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.networkxml.ImageLoader.DisplayImage(ImageLoader.java:42)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity.updateWeatherUi(MainActivity.java:129)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity.buildWeatherObject(MainActivity.java:172)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity.access$0(MainActivity.java:137)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity$1.onSuccess(MainActivity.java:195)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.loopj.android.http.AsyncHttpResponseHandler.handleSuccessMessage(AsyncHttpResponseHandler.java:160)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:173)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.loopj.android.http.AsyncHttpResponseHandler$1.handleMessage(AsyncHttpResponseHandler.java:85)
12-21 01:01:11.180: E/AndroidRuntime(28502): at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 01:01:11.180: E/AndroidRuntime(28502): at android.os.Looper.loop(Looper.java:150)
12-21 01:01:11.180: E/AndroidRuntime(28502): at android.app.ActivityThread.main(ActivityThread.java:4263)
12-21 01:01:11.180: E/AndroidRuntime(28502): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 01:01:11.180: E/AndroidRuntime(28502): at java.lang.reflect.Method.invoke(Method.java:507)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-21 01:01:11.180: E/AndroidRuntime(28502): at dalvik.system.NativeStart.main(Native Method)
Yikes! I tried to post a "snippet" but maybe I should've posted the complete file...
Putting the updateWeatherUi() logic at inside the end of buildWeatherObject() fixed this for me.
The problem is that I'm still not sure what was occurring here previously. The Logs were showing the proper data right up to the point of imageLoader.DisplayImage(String, ImageView) in my original code but I kept crashing there with NullPointerException.

Categories

Resources