Downloading Image from URL - android

I got a List View in my application in which I am displaying the data through Base Adapter. Their is two problems I am facing and referred few posts like but all suggested same procedure i followed.
Issues are
I am trying to download the image from the URL given from JSON. everything is working smoothly but the image never get set to Image View.
I bound Text to Speech on click event of button in Base Adapter class and freed it in onDestroy of of the java class but still I get a error in Log for it stating this and application crashes. Here in log erroe line no 55 is the first statement of onDestroy.
Here is my code
Java File
public class DisplayWeather extends Activity {
String city, date, maximumTemp, minimumTemp, description, weatherImageUrl;
ListView weatherList;
List <Bean> bean;
Bitmap myBitmap, newBitmap;
CustomBaseAdapter baseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_weather);
bean = new ArrayList<Bean>();
weatherList = (ListView) findViewById(R.id.lvWeather);
for(int i=0; i<WeatherHome.arrayList.size(); i++)
{
.
.
}
weatherList.setAdapter(new CustomBaseAdapter(this, bean));
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (baseAdapter.tts != null)
{
baseAdapter.tts.stop();
baseAdapter.tts.shutdown();
}
super.onDestroy();
}
Base Adapter class
public class CustomBaseAdapter extends BaseAdapter implements OnInitListener {
Context context;
List<Bean> bean;
ImageView weatherImage;
TextView weatherDate, weatherCity, weatherMinimum, weatherMaximum, weatherDescription;
Button buttonSpeak;
String citySpeak, dateSpeak, descriptionSpeak, maximumSpeak, minimumSpeak, weatherURL;
TextToSpeech tts;
Bean userBean;
Bitmap myBitmap;
public CustomBaseAdapter(Context context, List<Bean> bean) {
// TODO Auto-generated constructor stub
this.context = context;
this.bean = bean;
tts = new TextToSpeech(context, null);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return bean.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return bean.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return bean.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView == null)
{
convertView = inflater.inflate(R.layout.custom_base_adapter, null);
weatherImage = (ImageView) convertView.findViewById(R.id.displayImage);
convertView.findViewById(R.id.displayDate);
buttonSpeak = (Button) convertView.findViewById(R.id.Speak);
}
weatherURL = userBean.getImageUrl();
new ImageDownload().execute();
Log.i("Executing Rest Line>>>", "Skippedddddd");
buttonSpeak.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String cityName = weatherCity.getText().toString();
String dateValue = weatherDate.getText().toString();
String maximumValue = weatherMaximum.getText().toString();
String minimumValue = weatherMinimum.getText().toString();
String descriptionValue = weatherDescription.getText().toString();
citySpeak = "Temprature for city "+cityName+"";
dateSpeak = " on Date "+dateValue+"";
maximumSpeak = "will be Maximum upto "+maximumValue+" degree ";
minimumSpeak = " and Minimum upto"+minimumValue+" degree ";
descriptionSpeak = "and The atmosphere seems to be "+descriptionValue+"";
speakTempratureValues();
}
});
return convertView;
}
private class ImageDownload extends AsyncTask<String, Void, Bitmap>{
protected Bitmap doInBackground(String... arg0){
try{
Log.e("src",weatherURL);
URL url = new URL(weatherURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
}
catch(Exception e){
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Bitmap result){
if(result!=null)
{
Log.i("OnPost>>>", ""+result);
weatherImage.setImageBitmap(result);
}
}
}
protected void speakTempratureValues() {
// TODO Auto-generated method stub
tts.setSpeechRate(-4);
tts.speak(citySpeak, TextToSpeech.QUEUE_FLUSH, null);
tts.speak(dateSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak(maximumSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak(minimumSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak(descriptionSpeak, TextToSpeech.QUEUE_ADD, null);
tts.speak("Thank You", TextToSpeech.QUEUE_ADD, null);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status==TextToSpeech.SUCCESS){
int result = tts.setLanguage(Locale.getDefault());
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
else{
speakTempratureValues();
}
}
else{
Log.e("TTS", "Initialization Failed");
}
}
}

It looks like maybe you're returning your convertView in the getView method before your AsyncTask is finished downloading the image. Can you use a thread instead, and use the Thread join method so that your app waits for the image to be downloaded? For an AsyncTask you usually use a progress dialog until the task is finished, but I don't think you can do that inside of an adapter.
How about replacing this:
new ImageDownload().execute();
with this:
new Thread(new Runnable() {
public void run() {
try{
Log.e("src",weatherURL);
URL url = new URL(weatherURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned");
return myBitmap;
}
catch(Exception e){
e.printStackTrace();
return null;
}}
}).join();
and then obviously get rid of the ImageDownload class. I'm just throwing this at you, didn't test it or anything. I think that should get you closer.

What Louis suggested is the correct way. I am sure this will work. The reason why it's not working for you is not sure but try this way:
Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try{
Log.e("src",weatherURL);
URL url = new URL(weatherURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
myBitmap = BitmapFactory.decodeStream(input);
Log.e("Bitmap","returned"+myBitmap);
if(myBitmap!=null)
{
Log.i("OnPost>>>", ""+myBitmap);
weatherImage.setImageBitmap(myBitmap);
}
}
catch(Exception e){
e.printStackTrace();
}
}
};
Thread t = new Thread(runnable);
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Probably, the start method was missing for you and you might not have called it.
I hope this work.

Related

second fragment run in first fragment and third in second

My requierment is when I click the button in firstfragment load meaning from database ,then screen move to next screen (swipe to secondfragment) automaticaly image load from given url and display in image, then swipe to thirdfragment automatically audio load from given url, and same task for video.
Given code imagefragment(second fragment) load in meaningfragment(first fragment) and third in second, and fourth in third.
***Meaning fragment( First Fragment)***
String url2 = "";
String webdata = "";
int wifi = 0;
int first = 1;
View view;
List<String> wordslist;
ImageButton find;
EditText word;
WebView data;
TextView urdu_meaning;
ListView lv;
SqlLiteDbHelper dbHelper;
GetMeaning urdu ;
NetworkInfo mWifi;
ConnectivityManager connManager;
WifiManager wifiManager;
public static String urlword = "";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
view = inflater.inflate(R.layout.meaningview, container, false);
word = (EditText) view.findViewById(R.id.word);
find = (ImageButton) view.findViewById(R.id.find);
data = (WebView) view.findViewById(R.id.web);
urdu_meaning = (TextView) view.findViewById(R.id.Urdu_Text);
lv = (ListView) view.findViewById(R.id.listofword);
Typeface tf= Typeface.createFromAsset(getActivity().getAssets(), "jameel.ttf");
urdu_meaning.setTypeface(tf);
if(first == 1)
{
try {
dbHelper = new SqlLiteDbHelper(getActivity());
dbHelper.CopyDataBaseFromAsset();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
first++;
}
word.addTextChangedListener(new TextWatcher() {
#SuppressWarnings("static-access")
#SuppressLint("InlinedApi")
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
if (!word.getText().toString().equalsIgnoreCase(""))
{
wordslist = dbHelper.Loadwords(word.getText().toString());
//wordslist.toString()
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_selectable_list_item, wordslist);
lv.setVisibility(view.VISIBLE);
lv.setAdapter(adapter);
data.setVisibility(view.INVISIBLE);
urdu_meaning.setVisibility(view.INVISIBLE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#SuppressWarnings("static-access")
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
word.setText(wordslist.get(position));
lv.setVisibility(view.INVISIBLE);
}
});
find.setOnClickListener(new OnClickListener() {
#SuppressWarnings("static-access")
#SuppressLint({ "NewApi", "DefaultLocale" })
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
lv.setVisibility(view.INVISIBLE);
data.setVisibility(view.VISIBLE);
urdu_meaning.setVisibility(view.VISIBLE);
url2 = word.getText().toString().toLowerCase();
AudioFragment.audioclick = 0;
VideoFragment.videoclick = 0;
ImageFragment.imageclick = 0;
urlword = url2;
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if(url2.isEmpty())
{
Toast.makeText(getActivity(), "Word is missing! ", Toast.LENGTH_LONG).show();
}
else
{
try{
urdu = dbHelper.getDetail(word.getText().toString());
urdu_meaning.setText(urdu.Meaning.toString());
}catch(Exception e){
e.printStackTrace();
urdu_meaning.setText("Urdu word not found");
}
if (mWifi.isConnected())
{
data.loadUrl(url1 + url2);
}
else
{
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
//wifiManager.setWifiEnabled(true);
}
}
}
});
return view;
}
***Image Fragment Second Fragment***
if(imageclick == 0)
{
//imageURL1 = imageURL + MeaningFragment.urlword + ".jpg";
word.setVisibility(View.INVISIBLE);
// Execute the task
//GetXMLTask task = new GetXMLTask();
//task.execute(imageURL1);
// Create an object for subclass of AsyncTask
}
find.setOnClickListener(new OnClickListener() {
#SuppressWarnings("static-access")
#SuppressLint({ "NewApi", "DefaultLocale" }) #Override
public void onClick(View v) {
if(imageclick == 0)
{
imageURL2 = MeaningFragment.urlword.toString().toLowerCase();
word.setVisibility(View.VISIBLE);
word.setText(MeaningFragment.urlword.toString().toLowerCase());
prevword.setVisibility(View.INVISIBLE);
}
else
{
word.setVisibility(View.VISIBLE);
prevword.setVisibility(View.INVISIBLE);
imageURL2 = word.getText().toString().toLowerCase();
}
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
if(imageURL2.isEmpty())
{
Toast.makeText(getActivity(), "Word is missing! ", Toast.LENGTH_LONG).show();
imageView.setVisibility(View.INVISIBLE);
}
else
{
imageURL2 = imageURL2 + ".jpg";
imageURL1 = (imageURL + imageURL2);
//searchurdu();
if(mWifi.isConnected())
{
try{
// Execute the task
GetXMLTask task = new GetXMLTask();
task.execute(imageURL1);
// Create an object for subclass of AsyncTask
}catch(Exception e){
e.printStackTrace();
}
//task.execute("http://www.learn2crack.com/wp-content/uploads/2014/04/node-cover-720x340.png");
// TODO Auto-generated method stub
}
else
{
Toast.makeText(getActivity(), "Network Problem", Toast.LENGTH_LONG).show();
//wifiManager.setWifiEnabled(true);
}
}
}
});
return view;
}
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
try{
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}return map;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
//pDialog.show();
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
imageView.setVisibility(View.VISIBLE);
pDialog.dismiss();
if(result == null){
Toast.makeText(getActivity(), "Image Not Found", Toast.LENGTH_LONG).show();
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
try {Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
return bitmap;
} catch (IOException e1) {
e1.printStackTrace();
return null;
}
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
try {InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}return stream;
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(getActivity(), " Word not Found", Toast.LENGTH_LONG).show();
return null;
}
and same method for audio and video.....

null pointer exception in AQuery (Android query) function

In my code I used AQUery library to load image from web but it is showing null pointer exception at "aq.id(R.id.img);" in my code ...in class i created globle object of AQuery class and i define function inside inner class methode.....null pointer exception at "aq.id(R.id.img)" which is inside getview methode of cusomgrid class..
public class Customgrid extends Activity {
public int gotbread;
public int get, send;
AQuery aq;
String url1[] = { "https://www.dropbox.com/s/f308a9s5ycuc3mh/1.jpg",
"https://dl.dropbox.com/s/2s60g4e696566nt/2.jpg",
"https://dl.dropbox.com/s/59t6wo83ekzff0y/3.jpg",
"https://dl.dropbox.com/s/1b58qtj4ftm87yc/4.jpg",
"https://dl.dropbox.com/s/py7ogwstc0814zg/5.jpg",
"https://dl.dropbox.com/s/ocavtv1tkr6wtvv/6.jpg" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.customgview);
AQuery aq = new AQuery(Customgrid.this);
// Bundle gotbasket = getIntent().getExtras();
// gotbread = gotbasket.getInt("pos");
gotbread = getIntent().getExtras().getInt("position");
get = gotbread;
GridView grdview = (GridView) findViewById(R.id.gridView);
grdview.setAdapter(new Customgridadapter(this));
grdview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Bundle basket = new Bundle();
basket.putInt("position", send);
Intent i = new Intent(Customgrid.this,
FullScreenImageActivity.class);
i.putExtras(basket);
startActivity(i);
}
});
grdview.setVerticalSpacing(0);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
public class Customgridadapter extends BaseAdapter {
public Integer[] images1 = { R.drawable.s_1, R.drawable.s_2,
R.drawable.s_3 };
public Integer[] images2 = { R.drawable.s_5, R.drawable.s_6,
R.drawable.s_4 };
Context m1Context;
public Customgridadapter(Context context) {
super();
this.m1Context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return images1.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
int pos = 0;
LayoutInflater inflater = ((Activity) m1Context)
.getLayoutInflater();
View customRow1 = inflater.inflate(R.layout.gview, null);
ImageView image = (ImageView) customRow1
.findViewById(R.id.imageforgrid);
aq.id(R.id.imageforgrid);
aq.image(url1[0],true,true);
Bitmap bm = DownloadImage(url1[0]);
switch (gotbread) {
case 0:
image.setImageBitmap(bm);
break;
case 1:
image.setImageBitmap(bm);
break;
}
image.setAdjustViewBounds(true);
image.setScaleX((float) 0.9);
image.setScaleY((float) 0.9);
switch (get) {
case 0:
send = get + position;
break;
case 1:
send = 10 * 1 + position;
break;
case 2:
send = 10 * 2 + position;
break;
case 3:
send = 10 * 3 + position;
break;
case 4:
send = 10 * 4 + position;
break;
}
// image.setOnClickListener(new OnImageClickListener(position));
return customRow1;
}
}
You have
AQuery aq = new AQuery(Customgrid.this); // declared and initialized in oncreate
in onCreate becomes local to onCreate.
Change to
aq = new AQuery(Customgrid.this);
The instance variable aq was never initialized giving NPE.
public class Customgrid extends Activity {
public int gotbread;
public int get, send;
AQuery aq; // not initialized
Also no network related operation on the ui thread.

Android - Json and TwitterFeed code

Hi this is my first app.
I am a beginner when it comes to programming and to android.
My app is similar to the twitter app. But instead of getting values from twitter it would get values from my database. The app will be loaded with images and links to web pages.
My question.
Lets say my app is on the app store and someone downloads it.
My app get most of its content from my mysql db via Json. Every time i add new content to the db, must the user update the app to get the new content or will it automatically update its self.
Can someone just take a look at my code. I am not sure about the Async() and the doInBackground(). If you have any other helpful coding suggestions please let me know. I would like to put this app on the app store when it is complete.
Kind regards
public class TwitterFeedActivity extends ListActivity {
private ArrayList<Tweet> tweets = new ArrayList<Tweet>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TwitterFeedActivity.this,
"", "Loading. Please wait...", true);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
HttpClient hc = new DefaultHttpClient();
HttpGet get = new HttpGet("http://myurl.com");
HttpResponse rp = hc.execute(get);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
String result = EntityUtils.toString(rp.getEntity());
JSONObject root = new JSONObject(result);
JSONArray sessions = root.getJSONArray("results");
for (int i = 0; i < sessions.length(); i++) {
JSONObject session = sessions.getJSONObject(i);
Tweet tweet = new Tweet();
tweet.n_text = session.getString("n_text");
tweet.n_name = session.getString("n_name");
tweet.Image = session.getString("Image");
tweets.add(tweet);
}
}
} catch (Exception e) {
Log.e("TwitterFeedActivity", "Error loading JSON", e);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
setListAdapter(new TweetListAdaptor(TwitterFeedActivity.this, R.layout.list_item, tweets));
}
}
private class TweetListAdaptor extends ArrayAdapter<Tweet> {
private ArrayList<Tweet> tweets;
public TweetListAdaptor(Context context, int textViewResourceId, ArrayList<Tweet> items) {
super(context, textViewResourceId, items);
this.tweets = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
final Tweet o = tweets.get(position);
TextView tt = (TextView) v.findViewById(R.id.toptext);
TextView bt = (TextView) v.findViewById(R.id.bottomtext);
ImageView image = (ImageView) v.findViewById(R.id.avatar);
bt.setText(o.n_name);
tt.setText(o.n_text);
image.setImageBitmap(getBitmap(o.Image));
image.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse(o.n_text));
startActivity(intent);
}
});
return v;
}
}
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception ex) {return null;}
}
}
Ok I am posting the Async related code. I hope, you will find it helping. First of all, make a class as follows:
package com.example.pre;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class JSONFunctions {
public String CreateCon(String url){
String res="";
try{
URL u=new URL(url);
HttpURLConnection con = (HttpURLConnection) u.
openConnection();
res=readStream(con.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
private String readStream(InputStream is) {
// TODO Auto-generated method stub
String result = "";
BufferedReader reader=null;
try{
reader = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = reader.readLine()) != null) {
result=result+line;
}
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}finally{
if(reader!=null)
{
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
}
Second in your main class, paste the following method:
private class PostTask extends AsyncTask<String, Integer, String>{
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
readJson();
//progress_dialog.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
JSONFunctions jsonf=new JSONFunctions();
str1=jsonf.CreateCon(cat_url);
return null;
}
}
where readJson is the method where you define your functionality and str1 is the string where you provide the address of the json. Don't forget call to the PostExecute class.

android:load images from url and show in gridview

i am making an app in which i have to get response from xml and i get image urls .Now i want to put images from urls into gridview but i dnt know how to extract images from urls and put in gridview.Any help will be appreciated.My code is as follows:
public class GalleryNewActivity extends Activity {
private ProgressDialog dialog;
GridView ga;
Element e;
Node elem;
public List<Drawable> pictures;
ImageView imageView;
static final String PREFS_NAME = "MyPrefs";
static final String USER_KEY = "user";
static final String Name = "name";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(isNetworkconn()){
new GetSPCAsyncTask().execute("");
}else{
showDialogOnNoInternet();
}
ga = (GridView)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));
imageView = (ImageView)findViewById(R.id.ImageView01);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return pictures.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.galleryitem, null);
imageView = (ImageView)v.findViewById(R.id.thumbImage);
imageView.setLayoutParams(new GridView.LayoutParams(200, 250));
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(2, 5, 2, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(pictures.get(position));
imageView.setTag(pics[position]);
return imageView;
}
private class GetPicsToNextPage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(GalleryNewActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String str = null;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
Intent intent = new Intent(getApplicationContext(), Flip3d.class);
startActivity(intent);
}
}
private boolean isNetworkconn(){
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
return true;
}else{
return false;
}
}
private void showDialogOnNoInternet(){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(GalleryNewActivity.this);
alt_bld.setTitle("Error.");
alt_bld.setMessage("Your phone is not connected to internet.");
alt_bld.setCancelable(false);
alt_bld.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alt_bld.show();
}
//loader for dynamic starts
private class GetSPCAsyncTask extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(GalleryNewActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
NodeList nodes = doc.getElementsByTagName("Image");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
e = (Element)nodes.item(i);
//map.put("Image", XMLfunctions.getValue(e, "Image"));
map.put("ImagePath", "Naam:" + XMLfunctions.getValue(e, "ImagePath"));
map.put("ImageHeadline", "Headline: " + XMLfunctions.getValue(e, "ImageHeadline"));
System.out.println(map.put("ImageHeadline", "Headline: " + XMLfunctions.getValue(e, "ImageHeadline")));
map.put("ImageDesc", "Desc: " + XMLfunctions.getValue(e, "ImageDesc"));
System.out.println(map.put("ImageDesc", "Desc: " + XMLfunctions.getValue(e, "ImageDesc")));
mylist.add(map);
Drawable d=LoadImageFromWebOperations();
pictures.add(d);
}
return xml;}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
private Drawable LoadImageFromWebOperations()
{
String path=XMLfunctions.getValue(e, "ImagePath");
try{
InputStream is = (InputStream) new URL(path).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
Log.w("CREADO","CREADO");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
}
I would suggest you to check below solutions for loading images from URL:
Android - Universal Image loader by Nostra
Lazy load of images in ListView
Result you can get if you use Universal image loader:
call this function with url you will get Drawable , and then store this drawables into custom class and then place in grid view.
call function like this
ImageOperations(this, imageurl)
public Object fetch(String address) throws MalformedURLException, IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper will fill an ImageView with an image that is found at a URL.
The sample will do a Google Image Search and load/show the results asynchronously.
UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.
else use this,
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}

Http image parsing problem

I'm trying to set different images by parsing, but I can set only last image. I don't know where the problem is in this code:
public class GridActivity extends Activity{
private EfficientAdapter adap;
String strUrl;
AddAlbumDetailBean aBean;
XmlParser parser;
ArrayList<Object> result;
ArrayList<Object> data;
ImageButton btnAdd;
private Context context;
static Bitmap bitmap;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
Utils.onActivityCreateSetTheme(this);
setContentView(R.layout.photos_activity);
GridView gView = (GridView)findViewById(R.id.gridview);
adap = new EfficientAdapter(this);
gView.setAdapter(adap);
/*btnAdd = (ImageButton)findViewById(R.id.btnAddPhotos);
btnAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(GridActivity.this,AddAlbum.class));
}
});
*/
}
public static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
String strUrl;
AddAlbumDetailBean aBean;
XmlParser parser;
ArrayList<Object> result;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
this.context = context;
String userId = ConstantData.user_id;
String albumId = ConstantData.album_id;
int pageNo = 1;
int limit = 20;
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=photo_paging&userid="+ ConstantData.user_id +"&sessionid="+ ConstantData.session_id +"&tmpl=component&albumid="+ ConstantData.album_id +"&pageno=1&limit=20");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><pageno>" + pageNo +"</pageno><limit>"+ limit +"</limit></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);
HttpResponse response = client.execute(post);
InputStream in = response.getEntity().getContent();
String strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "data");
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startT = strResponse.indexOf(startThumb);
int endT = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startT);
Log.i("endThumb", ""+endT);
String OldThumb = strResponse.substring(startT, endT);
int startUrlindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startUrlindex + 1).trim();// getting Url from webservice
Log.i("Thu0mb", ""+thumb);
URL newurl = new URL(thumb);
bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());// converting Url into Bitmap but dont know how to use bitmap array here
Log.d("Bitmap in ConstantData", ""+bitmap);
}
if (startUrl.equalsIgnoreCase("<url>") && endUrl.equalsIgnoreCase("</url>"))
{
int startL = strResponse.indexOf(startUrl);
int endL = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startL);
Log.i("endUrl", ""+endL);
String OldUrl = strResponse.substring(startL, endL);
int startUrlindex = OldUrl.indexOf(">");
String url = OldUrl.substring(startUrlindex + 1).trim();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.icon, null);
holder = new ViewHolder();
holder.iconImage = (ImageView) convertView.findViewById(R.id.icon_image);
convertView.setOnClickListener(new OnClickListener() {
private int pos = position;
#Override
public void onClick(View v) {
Toast.makeText(context, "Click-" + String.valueOf(pos), Toast.LENGTH_SHORT).show();
context.startActivity(new Intent(context,GridActivity.class));
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Log.d("Bitmap in ConstantData", ""+bitmap);
holder.iconImage.setImageBitmap(bitmap);
return convertView;
}
static class ViewHolder {
ImageView iconImage;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5; // if i m trying to return result.size(); getting error and returning 5 i can only get 5 images
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
public static String convertStreamToString(InputStream in)
throws IOException {
if (in != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}
Through this code i am trying to set image into the dynamic gridview using adapter....
but i can set only last image into the gridview so i dont know how to use bitmap array
There are a lot of problems on your code:
your bitmap is static, so you overriding it...
you have no loop, so you have only the same bitmap "parsed"
(after that I stopped looking)
Try to clean up your code and try to debug step by step so that you understand what your code does...
update:
some tips:
use AsyncTask to request the XML and parse it there
when finished fill the adapter with the parsed image urls

Categories

Resources