Performing Bitmap conversion in background - android

In my application, I want to perform Bitmap conversion in background as I am facing memory leak issue. I know, it can be done with Async Task but not getting idea how to do this. Below I am posting my code.
package com.android.album3;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class Album3Activity extends Activity
{
File [] mediaFiles;
File imageDir;
static GridView gridView;
ImageAdapter adapter;
Intent in;
String name = null;
ArrayList<Bitmap> bmpArray = new ArrayList<Bitmap>();
ArrayList<String> fileName = new ArrayList<String>();
public static final String TAG = "Album3Activity";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
imageDir = new File(Environment.getExternalStorageDirectory().toString()+
"/diplomat");
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
if(imageDir.exists())
{
setContentView(R.layout.grid);
mediaFiles = imageDir.listFiles();
//Log.d("Length of images",""+mediaFiles.length);
for(File file : mediaFiles)
{
bmpArray.add(convertToBitmap(file));
fileName.add(readFileName(file));
Log.d(TAG + "bmpArray Size", ""+bmpArray.size());
Log.d(TAG, "call to convertToBitmap");
}//for
adapter = new ImageAdapter(this, bmpArray, fileName);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3)
{
in = new Intent(getApplicationContext(), FullScreen.class);
in.putExtra("id", position);
startActivity(in);
}//onItemClick
});
}//if
else
{
setContentView(R.layout.no_media);
//Toast.makeText(Album3Activity.this, "No files available", Toast.LENGTH_SHORT).show();
}//else
}//onCreate
public static Bitmap convertToBitmap(File file)
{
URL url = null;
try
{
url = file.toURL();
}//try
catch (MalformedURLException e1)
{
Log.d(TAG, e1.toString());
}//catch
Bitmap bmp = null;
try
{
bmp = BitmapFactory.decodeStream(url.openStream());
//bmp.recycle();
}//try
catch(Exception e)
{
Log.d(TAG, "Exception: "+e.toString());
}//catch
return bmp;
}//convertToBitmap
public String readFileName(File file)
{
String name = file.getName();
return name;
}//readFileName
}//class

Related

Deleted files are not effected to mobile while deleting from System over USB connection

I build an application to inserting the data into the file and saved in the internal memory and I used MediaScannerConnection class to visible the files in system while connecting the mobile to PC But if i deleted any file it is not effected to the mobile instantly
Here is my code:
package com.example.uhf.activity;
import android.app.Activity;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uhf.R;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;
public class Main3Activity extends Activity {
ArrayList<String> sel=new ArrayList<String>();
ArrayList<String> arrayList=new ArrayList<String>();
Button button,mergeandexport;
File myExternalFile;
private String filepath = "Folder";
ArrayList<String> FilesInFolder ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
button=(Button)findViewById(R.id.button);
mergeandexport=(Button)findViewById(R.id.mergeandexport);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
ListView list=(ListView)findViewById(R.id.listview);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
FilesInFolder = GetFiles("/sdcard/Folder");
ArrayAdapter<String> aa=new ArrayAdapter<String> (this,R.layout.rowlayout,R.id.checked,FilesInFolder.toArray(new String[0]));
list.setAdapter(aa);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String string = ((TextView) view).getText().toString();
if(sel.contains(string)){
sel.remove(string);
}
else {
sel.add(string);
}
}
});
mergeandexport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
marged();
}
});
}
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
//f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=files.length-1; i>=0; i--)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
public void marged(){
try {
BufferedReader br=null;
String line;
for (int i=0;i<sel.size();i++){
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/sdcard/" + filepath,sel.get(i).toString()))));
while ((line = br.readLine()) != null) {
arrayList.add(line);
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
if(arrayList.size()==0){
Toast.makeText(this,"Choose more than one files",Toast.LENGTH_SHORT).show();
}
else if(arrayList.size()==1){
Toast.makeText(this,"Choose more than one files",Toast.LENGTH_SHORT).show();
}
else {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH-mm-ss");
String filename = formatter.format(Calendar.getInstance().getTime()).replace(" ", "_") + ".txt";
myExternalFile = new File("/sdcard/" + filepath, "Merged " + filename);
try {
// add elements to al, including duplicates
Set<String> hs = new HashSet<String>();
hs.addAll(arrayList);
arrayList.clear();
arrayList.addAll(hs);
FileOutputStream fos = new FileOutputStream(myExternalFile);
MediaScannerConnection.scanFile(this, new String[] {myExternalFile.toString()}, null, null);
for (int i = 0; i < arrayList.size(); i++) {
String extra = arrayList.get(i) + "\n";
fos.write(extra.getBytes());
}
fos.close();
} catch (IOException e) {
e.printStackTrace();
}``
Toast.makeText(this, "File is saved in "+filepath, Toast.LENGTH_LONG).show();
}
}
}

java.lang.IllegalStateException: Method call should not happen from the main thread. error in OnClick when using Picasso

I am making a wallpaper app, I want to set image from url as wallpaper.
I assigned url by using
url = intent.getStringExtra("tmp");
from previous activity. I called this code in onClick method.
Bitmap result ;
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
result= Picasso.with(this)
.load(url)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
I am using picasso library to set image as wallpaper but I have a problem that I couldn't understand why this error occurs.
Not: ImageLoader is another class to display images.
Activity:
package gc.x;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.IOException;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
ImageLoader imageLoader;
ImageView image;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = this.getIntent();
// intent.getStringExtra("tmp");
image = (ImageView)findViewById(R.id.image4) ;
Button button = (Button) findViewById(R.id.button1);
imageLoader = new ImageLoader(this.getApplicationContext());
url = intent.getStringExtra("tmp");
imageLoader.DisplayImage(url, image);
if(button != null)
button.setOnClickListener(SecondActivity.this);
}
#Override
public void onClick(View v) {
Bitmap result ;
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
result= Picasso.with(this)
.load(url)
.get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
EDIT:
I tried a solution but it is not working. It does not give error, but nothing happens when I click the button. My New Code:
package gc.x;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
ImageLoader imageLoader;
ImageView image;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = this.getIntent();
// intent.getStringExtra("tmp");
image = (ImageView)findViewById(R.id.image4) ;
Button button = (Button) findViewById(R.id.button1);
imageLoader = new ImageLoader(this.getApplicationContext());
url = intent.getStringExtra("tmp");
imageLoader.DisplayImage(url, image);
if(button != null)
button.setOnClickListener(SecondActivity.this);
}
#Override
public void onClick(View v) {
new SetWallpaperTask();
Toast.makeText(getApplicationContext(), "Set wallpaper successfully", Toast.LENGTH_SHORT).show();
}
public class SetWallpaperTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
Bitmap result= null;
try {
result = Picasso.with(getApplicationContext())
.load("https://www.geektopia.es/storage/geek/posts/2015/08/17/marshmallow.jpg")
.get();
} catch (IOException e) {
e.printStackTrace();
}
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute (Bitmap result) {
super.onPostExecute(result);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getBaseContext());
try {
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
#Override
protected void onPreExecute () {
super.onPreExecute();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
I defined a method that returns bitmap from url
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Then a new thread in OnClick method to prevent android.os.NetworkOnMainThreadException error.
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
Bitmap bitmap= getBitmapFromURL(url);
if(bitmap!=null)
myWallpaperManager.setBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
Final Activity:
package gc.x;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class SecondActivity extends Activity {
ImageLoader imageLoader;
ImageView image;
String url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent = this.getIntent();
// intent.getStringExtra("tmp");
image = (ImageView)findViewById(R.id.image4) ;
Button button = (Button) findViewById(R.id.button1);
imageLoader = new ImageLoader(this.getApplicationContext());
url = intent.getStringExtra("tmp");
imageLoader.DisplayImage(url, image);
if(button != null)
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
Bitmap bitmap= getBitmapFromURL(url);
if(bitmap!=null)
myWallpaperManager.setBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
}
EDIT: original question was a simple handling of an exception. Once handled it revealed further problems in the code which the OP has changed his question to reflect. Without mention of his original question.
Placing
Bitmap result= Picasso.with(this) //XX Problem Occurs Here
.load("url")
.get();
Inside the IOException try/catch should fix this.
Imagine there is nothing to load().get() you would have an IOException. Since the possibility exists you need to handle it in case it happens.
#Override
public void onClick(View v) {
Bitmap result;
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
try {
result = Picasso.with(this).load("url").get();
wallpaperManager.setBitmap(result);
} catch (IOException ex) {
ex.printStackTrace();
}
}
Doing this should handle the exception.

Need help regarding integrating android functions with premade views

I'm just new to android and java and i m trying to build a sample android application.
I picked up application view from androhive looks like google+ app
and made my function following to many tutorials online
but i'm unable to integrate them.
here are my codes
Here is my fragment sample which is used in switching activity using sidebar
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MHEFragment extends Fragment {
public MHEFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
return rootView;
}
}
Heres my function os listview
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
private String jsonResult;
private String url = "http://192.168.129.1/1.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> storyList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("story");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("story_name");
String number = jsonChildNode.getString("story_id").toString();
String outPut = number + "-" + name;
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View name, int position,
long number) {
Intent intnt = new Intent(getApplicationContext(), Tester.class);
String deta = adapter.getItemAtPosition(position).toString();
String myStr = deta.replaceAll( "[^\\d]", "" );
intnt.putExtra(EXTRA_MESSAGE,myStr);
startActivity(intnt);
}
});
storyList.add(createStory("stories", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, storyList,
android.R.layout.simple_list_item_1,
new String[] { "stories" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createStory(String name, String number) {
HashMap<String, String> storyNameNo = new HashMap<String, String>();
storyNameNo.put(name, number);
return storyNameNo;
}
}
How can i integrate my listview in above fragment?
If you want ListView in fragment then you'd be better off using your Fragment which would subclass ListFragment.
And the onCreateView() from ListFragment will return a ListView that you can populate.
http://developer.android.com/reference/android/app/ListFragment.html
http://www.vogella.com/tutorials/AndroidListView/article.html#listfragments
For Fragments, if you want a separate ListView and more in one fragment, it'l help if you go through:
http://www.easyinfogeek.com/2013/07/full-example-of-using-fragment-in.html
..for what is more to the layout and calling onCreateView()
Also, (not a part of the question, but from & for your code) if it helps, i'd suggest
Use a for each loop where you can instead of for(;;)
(in your case at: for each json child node in json main node)
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?

Getting image from network using bitmap

We know that each YouTube video has an image . We can get the source of that image using jsonc file. I have written a code to get the source of that image and then store it in a string in order to use bit map to put it in an image view in my costume list view.
In parsing I have no problem I can store the source of the image.
But when my costume view is on view the image did not appear in it.
I have been told that getting the image from the network is very very bad thing and not to do network call on UI thread .
And I should and must use some library to manage and cache bitmaps.
What can I do in order to solve this?
Here is my main activity where I did the parsing from jsonc file:
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.example.tstnetconnwithjson.tables.custome;
import com.example.tstnetconnwithjson.tables.videos;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
Button search; ;
TextView name ;
ListView listview ;
ArrayList<videos > videolist;
ArrayAdapter< videos > adapter ;
AlertDialog.Builder alert ;
ProgressDialog progressdialog ;
EditText name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videolist = new ArrayList<videos>();
adapter = new ArrayAdapter<videos>(this, android.R.layout.simple_list_item_1 , android.R.id.text1,videolist);
name=(EditText) findViewById(R.id.editText1);
alert = new Builder(this);
alert.setTitle("Warnning" ) ;
alert.setMessage("You want to connect to the internet ..? " );
alert.setNegativeButton("No ", null);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String username=name.getText().toString();
new connection().execute("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
}
});
progressdialog = new ProgressDialog(this);
progressdialog.setMessage("Wait Loading .... ");
progressdialog.setCancelable(false);
search = (Button) findViewById(R.id.button1);
name = (TextView) findViewById(R.id.textView1);
listview = (ListView) findViewById(R.id.listView1);
listview.setAdapter(adapter);
search.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
alert.show();
}
});
}
class connection extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
progressdialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
String s = GetUrlBody(arg0[0]);
return s;
}
#Override
protected void onPostExecute(String result) {
try{
JSONObject jo =(JSONObject) new JSONTokener(result).nextValue();
JSONObject feed = jo.optJSONObject("data");
JSONArray entry = feed.optJSONArray("items");
for(int i = 0 ; i<entry.length() ; i++){
String title = entry.getJSONObject(i).getString("title");
String thumbURL = entry.getJSONObject(i).getJSONObject("thumbnail").getString("sqDefault");
Log.d("after get image", "ok")
String url;
try {
url = entry.getJSONObject(i).getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = entry.getJSONObject(i).getJSONObject("player").getString("default");
}
String description = entry.getJSONObject(i).getString("description");
Log.d("after get description", "ok");
videos videoobject=new videos();
videoobject.setDecscrption(description);
videoobject.setImageurl(thumbURL);
videoobject.setVediourl(url);
videoobject.setVideoname(title);
videolist.add(videoobject);
}
listview.setAdapter(new custome(MainActivity.this,videolist));
Log.d("AFTER set custome ", "before notify changes");
adapter.notifyDataSetChanged();
}catch(Exception exception) {
Log.d("exception ", "nock nock nock....");
Log.e("json ", exception.getMessage());
}
progressdialog.dismiss();
super.onPostExecute(result);
}
String GetUrlBody (String Url ){
HttpClient client = new DefaultHttpClient();
HttpGet gethttp = new HttpGet(Url);
try{
HttpResponse response = client.execute(gethttp);
if(response.getStatusLine().getStatusCode() == 200){
String save =
EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
return save;
}else {
return "Not Found";
}
}catch(Exception exception){}
return null;
}
}
}
And here is my costume list-view:
public class custome extends BaseAdapter {
ArrayList<videos> data=new ArrayList<videos>();
android.content.Context context1;
android.widget.TextView name;
ImageView picture;
public custome(Context context,ArrayList<videos>arrayList) {
// TODO Auto-generated constructor stub
context1=context;
data= arrayList;
}
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
public View getView(int arg0, View arg1, ViewGroup arg2) {
View view=arg1;
if(view==null)
{
LayoutInflater layoutInflater=(LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view=layoutInflater.inflate(R.layout.listvideo,null);
}
name=(TextView) view.findViewById(R.id.textView1);
picture=(ImageView) view.findViewById(R.id.imageView1);
videos video = data.get(arg0);
name.setText(video.getVideoname());
URL url = null;
try {
url = new URL(video.getImageurl());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
picture.setImageBitmap(bitmap);
return view;
}
}
I suggest you use Thread to download image from network & get InputStream and then parse to Bitmap.
Full project is here: E4U Project
import java.io.InputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Downloading images from the net for display, with possible requirement of caching is a very common problem that many people have solved, I would strongly recommend you to use one of these tried and working solutions instead of rolling & debugging your own solution:
Ion (https://github.com/koush/ion) - very flexible and feature complete, plus it can download more than images but JSON, Strings, Files, and Java types as well. The part that I really like about this is that it can automatically cancel operations when the calling Activity finishes, so users don't waste time & bandwidth downloading images that will no longer be displayed
Universal Image Loader (https://github.com/nostra13/Android-Universal-Image-Loader) - equally capable for most use cases but for downloading/caching images only

Struggling to Download Files using Android Eclipse?

I am struggling to make a simple app to download files of the internet heres my code I have edited a little from another question but I am still getting not responding errors whenever I run my app can any one show me the correction or even a different way?
package com.example.downloading;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.util.ByteArrayBuffer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ResultReceiver;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.IntentService;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
public class MainActivity extends Activity {
Button startBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startBtn = (Button)findViewById(R.id.download_button);
startBtn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String url = "my stuff";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("descrition");
request.setTitle("title");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "etc.mp3");
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
});
}
}
public void DownLoadTheMusic(){
try {
URL url = new URL("http://www.tagsinfosoft.com/android/shelf/Shelf_Cam.mp3");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/";
File file = new File(PATH);
file.mkdirs();
File outputFile = new File(file, "Shelf_Cam.mp3");
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Update error!", Toast.LENGTH_LONG).show();
}
}
call this in a Asynctask
public class downloadMusic extends AsyncTask<Integer, Integer, Integer>
{
#Override
protected Integer doInBackground(Integer... params) {
// TODO Auto-generated method stub
try {
DownLoadTheMusic();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Context context=shelf.this;
pd.dismiss();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "Shelf_Cam.mp3")), "application/vnd.android.package-archive");
startActivity(intent);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pd=ProgressDialog.show(shelf.this,"Updating","Please wait....." );
}
}
execute this task onbutton click use this if you are downloading small music file from internet.

Categories

Resources