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.....
Related
I have a list where for each item i need to display a image. I am downloading the image from a link and displaying it but with i am facing problems to display them as the list gets populated by text first and then downloads the images later.Also another problem is whenever i go up or down in the list image disappears and download again so the images are gone when i come to to the top the list items
EventTask
public RecieveEventsTask(EventListActivity c, String critiria) {
appContext = c;
session = new SessionManager(appContext);
HashMap<String, String> user = session.getUserDetails();
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/geteventlist?user_id=" + id;
}
public RecieveEventsTask(MyEventList c, String critiria) {
my_appContext = c;
session = new SessionManager(my_appContext);
HashMap<String, String> user = session.getUserDetails();
// id
String id = user.get(SessionManager.KEY_ID);
url = "http://bioscopebd.com/mobileappand/getmyeventlist?user_id=" + id;
}
protected void onPreExecute() {
dialog = new ProgressDialog(appContext == null ? my_appContext
: appContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Events...");
dialog.show();
super.onPreExecute();
}
String filterResponseString(String r) {
return r.replace("\r\n", "");
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
try {
response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
responseString = filterResponseString(responseString);
} else {
// Closes the connection.
response.getEntity().getContent().close();
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
} catch (Exception e) {
// TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
if (responseString != null) {
ArrayList<EventModel> eventsList = new ArrayList<EventModel>();
;
JSONArray jsonArr;
try {
// Log.v("json", responseString);
jsonArr = new JSONArray(responseString);
// jsonArr = events.getJSONArray("events");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
EventModel event = new EventModel();
event.setTitle(jsonObj.getString("event_info_title"));
event.setDescription(jsonObj.getString("event_info_desc"));
// Log.v("logo data "+i, jsonObj.getString("image_logo"));
event.setBanner(jsonObj.getString("image_banner"));
event.setLogo(jsonObj.getString("image_logo"));
// event.setDescription(jsonObj.getString("event_info_desc"));
event.setCategory(jsonObj.getString("event_cat_title"));
event.setStartDate(jsonObj
.getString("event_info_start_date"));
event.setEndDate(jsonObj.getString("event_info_end_date"));
event.setStartTime(jsonObj
.getString("event_info_start_time"));
event.setEndTime(jsonObj.getString("event_info_end_time"));
event.setEventId(jsonObj.getString("event_info_id"));
event.setPhone(jsonObj.getString("event_info_mobile"));
event.setEmail(jsonObj.getString("event_info_email"));
event.setWeblink(jsonObj.getString("event_info_web"));
//
// logoDownloader = new ImageDownloader(event.getLogoBitmap());
// logoDownloader.execute(event.getLogo());
//
// bannerDownloader = new ImageDownloader(event.getBannerBitmap());
// bannerDownloader.execute(event.getBanner());
//
eventsList.add(event);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (appContext != null) {
appContext.showEventsDataLoaded(eventsList);
}
if (my_appContext != null) {
my_appContext.showEventsDataLoaded(eventsList);
}
// else
// {
// Log.v("check:","null");
//
// }
//
} else {
if(appContext!=null)
{
Utility.showMessage(appContext, "Cannot Connect To Internet");
}
else {
Utility.showMessage(my_appContext, "Cannot Connect To Internet");
}
//
}
super.onPostExecute(result);
// Do anything with response..
}
i get the image link in my setlogo and setbanner method
Adapter class
private final Activity context;
private final ArrayList<EventModel> events;
ImageDownloader imgDownloader;
Bitmap bitmap;
ImageView icon;
public EventsListAdapter(Activity context, ArrayList<EventModel> events) {
super(context, com.bioscope.R.layout.event_listitem, events);
this.context = context;
this.events = events;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(com.bioscope.R.layout.event_listitem,
null, true);
TextView title = (TextView) rowView
.findViewById(com.bioscope.R.id.title);
title.setText(events.get(position).getTitle());
TextView description = (TextView) rowView
.findViewById(com.bioscope.R.id.description);
description.setText(events.get(position).getDescription());
TextView category = (TextView) rowView
.findViewById(com.bioscope.R.id.category);
category.setText(events.get(position).getCategory());
Log.v("logo", events.get(position).getLogo());
icon = (ImageView) rowView
.findViewById(com.bioscope.R.id.event_icon);
//imgDownloader = new ImageDownloader(icon);
new LoadImage().execute(events.get(position).getLogo());
//ImageLoader.displayImage(events.get(position).getLogo().toString(), icon);
return rowView;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// pDialog = new ProgressDialog(MainActivity.this);
// pDialog.setMessage("Loading Image ....");
// pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
icon.setImageBitmap(image);
//pDialog.dismiss();
}else{
//pDialog.dismiss();
// Toast.makeText(EventListActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
// icon.set
}
}
}
}
i am setting the image in my icon of list items
Activity class
private ListView list;
private MenuItem myActionMenuItem;
private EditText myActionEditText;
private TextView myActionTextView;
private AutoCompleteTextView actv;
// private Spinner spinner;
private Button liveEvent;
private ArrayList<EventModel> eventsList;
private static final String[] paths = { "All", "Favourites" };
private ArrayList<String> array_sort;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.bioscope.R.layout.eventlist);
RecieveEventsTask task = new RecieveEventsTask(this, "all");
task.execute();
}
public void showEventsDataLoaded(ArrayList<EventModel> eventsList) {
this.eventsList = eventsList;
// for(EventModel e:eventsList )
// {
// Log.v("title", e.getTitle());
// }
EventsListAdapter adapter = new EventsListAdapter(
EventListActivity.this, eventsList);
list = (ListView) findViewById(com.bioscope.R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
// Toast.makeText(EventList.this, "You Clicked an item ",
// Toast.LENGTH_SHORT).show();
showEventInformaion(position);
}
});
// RecieveCategoriesTask task = new RecieveCategoriesTask(this, "all");
// task.execute();
liveEvent = (Button) findViewById(R.id.liveEvent);
liveEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(EventListActivity.this,
LiveEventActivity.class);
startActivity(i);
}
});
}
public void showCategoryListDataLoaded(String response) {
Utility.showMessage(this, response);
}
Then in my activity i called the async reciver task to load all the data along with link and gave set them in my model class.
You haveto set ResponseCache in your Main class while downloading bitmap:
Like this:
try {
File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
long httpCacheSize = 10 * 1024 * 1024; // 10 MiB
HttpResponseCache.install(httpCacheDir, httpCacheSize);
} catch (IOException e) { }
and
connection.setUseCaches(true);
http://practicaldroid.blogspot.com/2013/01/utilizing-http-response-cache.html
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.
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.
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;
}
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