GridActivity.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class GridActivity extends Activity
{
ArrayList<String> imageurl=new ArrayList<String>();
String albumId= ConstantData.album_id;
String userId = ConstantData.user_id;
int pageNo =1;
int limit = 20;
ArrayList<Object> result;
XmlParser parser;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_activity);
//Add required urls
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", "photo");
//Log.i("aBean Value", ""+aBean);
//System.out.println(strResponse);
String startCode = "<code>";
String endCode = "</code>";
String starPhotoCount = "<photocount>";
String endPhotoCount ="</photocount>";
String starPhotos = "<photos>";
String endPhotos ="</photos>";
String startPhoto = "<photo>";
String endPhoto = "</photo>";
String startId = "<Id>";
String endId = "</Id>";
String starTitle = "<title>";
String endTitle ="</title>";
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startCode.equalsIgnoreCase("<code>") && endCode.equalsIgnoreCase("</code>"))
{
int startC = strResponse.indexOf(startCode);
int endC = strResponse.indexOf(endCode);
Log.i("startCode", ""+startC);
Log.i("endCode", ""+endC);
String OldCode = strResponse.substring(startC, endC);
int startCodeindex = OldCode.indexOf(">");
String code = OldCode.substring(startCodeindex + 1).trim();
Log.i("Code", ""+code);
}
if (starPhotoCount.equalsIgnoreCase("<photocount>") && endPhotoCount.equalsIgnoreCase("</photocount>"))
{
int startPC = strResponse.indexOf(starPhotoCount);
int endPC = strResponse.indexOf(endPhotoCount);
Log.i("starPhotoCount", ""+startPC);
Log.i("endPhotoCount", ""+endPC);
String OldPC = strResponse.substring(startPC, endPC);
int startPCindex = OldPC.indexOf(">");
String photocount = OldPC.substring(startPCindex + 1).trim();
Log.i("PhotoCount", ""+photocount);
}
if (starPhotos.equalsIgnoreCase("<photos>") && endPhotos.equalsIgnoreCase("</photos>"))
{
int startPs = strResponse.indexOf(starPhotos);
int endPs = strResponse.indexOf(endPhotos);
Log.i("starPhotos", ""+startPs);
Log.i("endPhotos", ""+endPs);
String OldPhotos = strResponse.substring(startPs, endPs);
int startPhotosindex = OldPhotos.indexOf(">");
String photos = OldPhotos.substring(startPhotosindex + 1).trim();
Log.i("Photos", ""+photos);
}
if (startPhoto.equalsIgnoreCase("<photo>") && endPhoto.equalsIgnoreCase("</photo>"))
{
int startP = strResponse.indexOf(startPhoto);
int endP = strResponse.indexOf(endPhoto);
Log.i("startPhoto", ""+startP);
Log.i("endPhoto", ""+endP);
String OldThumb = strResponse.substring(startP, endP);
int startUrlindex = OldThumb.indexOf(">");
String photo = OldThumb.substring(startUrlindex + 1).trim();
Log.i("Photo", ""+photo);
}
/*if (startId.equalsIgnoreCase("<id>") && endId.equalsIgnoreCase("</id>"))
{
int startI = strResponse.indexOf(startId);
int endI = strResponse.indexOf(endId);
Log.i("startId", ""+startI);
Log.i("endId", ""+endI);
String OldId = strResponse.substring(startI, endI);
int startIdindex = OldId.indexOf(">");
String id = OldId.substring(startIdindex + 1).trim();
Log.i("ID", ""+id);
}*/
if (starTitle.equalsIgnoreCase("<title>") && endTitle.equalsIgnoreCase("</title>"))
{
int startT = strResponse.indexOf(starTitle);
int endT = strResponse.indexOf(endTitle);
Log.i("startTitle", ""+startT);
Log.i("endTitle", ""+endT);
String OldTitle = strResponse.substring(startT, endT);
int startTitleindex = OldTitle.indexOf(">");
String title = OldTitle.substring(startTitleindex + 1).trim();
Log.i("Title", ""+title);
}
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startTh = strResponse.indexOf(startThumb);
int endTh = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startTh);
Log.i("endThumb", ""+endTh);
String OldThumb = strResponse.substring(startTh, endTh);
int startthumbindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startthumbindex + 1).trim();
Log.d("Thumb Url", thumb);
imageurl.add(thumb);
Log.i("Thu0mb", ""+thumb);
}
if (startUrl.equalsIgnoreCase("<url>") && endId.equalsIgnoreCase("</url>"))
{
int startU = strResponse.indexOf(startUrl);
int endU = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startU);
Log.i("endUrl", ""+endU);
String OldUrl = strResponse.substring(startU, endU);
int startUrlindex = OldUrl.indexOf(">");
String strUrl = OldUrl.substring(startUrlindex + 1).trim();
Log.i("Url", ""+strUrl);
}
}
catch (Exception e) {
e.printStackTrace();
}
/*imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");*/
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
public int getCount() {
Log.i("SiZE of ImageUrl", ""+imageurl.size());
return imageurl.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
/*AddAlbumDetailBean aBean = (AddAlbumDetailBean)result.get(position);
imageurl.add(aBean.thumb);*/
String strURL=imageurl.get(position);
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
URL url;
try {
url = new URL(strURL);
URLConnection conn = url.openConnection();
in=conn.getInputStream();
Bitmap bitmap1= BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bitmap1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//imageView.setImageResource(imagen]);
return imageView;
}
}
public 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 "";
}
}
}
XMLParser.java
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XmlParser extends DefaultHandler{
public String RootElement;
public String RecordElement;
public InputStream in;
public Object mainObj;
public Object newObj;
public boolean inProcess;
public String xmlURL;
public ArrayList<Object> Records = null;
private final String TAG = "XmlParser";
StringBuffer buffer = new StringBuffer();
String elementName;
String elementValue;
public XmlParser(InputStream is,Object tempObj)
{
in = is;
mainObj = tempObj;
Log.i("Object value", ""+mainObj);
inProcess = false;
}
public XmlParser(String strURL,Object tempObj)
{
xmlURL = strURL;
mainObj = tempObj;
inProcess = false;
}
public ArrayList<Object> ParseUrl(String rootElement ,String recordElement)
{
RootElement = rootElement;
Log.i("RootElement",RootElement);
RecordElement = recordElement;
Log.i("RecordElement", RecordElement);
try
{
URL sourceUrl = new URL(xmlURL);
Log.d("URl", xmlURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
reader.setContentHandler(this);
reader.parse(new InputSource(sourceUrl.openStream()));
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return this.Records;
}
public ArrayList<Object> parse(String rootElement, String recordElement)
{
RootElement = rootElement;
RecordElement = recordElement;
Log.i("Root Element", ""+RootElement);
Log.i("Record Element", ""+RecordElement);
try{
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(in, this);
}catch(Exception e){
e.printStackTrace();
return null;
}
return this.Records;
}
#Override
public void startElement(String Uri, String localName,String qName,Attributes attributes) throws SAXException
{
Log.d("URl", xmlURL);
elementValue = "";
Log.i("IN STARTELEMENT", ""+elementValue);
if(localName.length() > 0)
{
Log.i("Local Name Length", ""+localName.length());
Log.i("LocalName", ""+localName);
if(localName.equalsIgnoreCase(RootElement))
{
Records = new ArrayList<Object>();
Log.i("Root element", ""+RootElement);
Log.i("Records", ""+Records);
}
else if(localName.equalsIgnoreCase(RecordElement))
{
newObj = ClassUtils.newObject(mainObj);
Log.i("Main Object", ""+mainObj);
Log.i("Record element", ""+RecordElement);
ClassUtils.objectMapping(newObj, localName, elementValue);
Log.i("Element Value", ""+elementValue);
inProcess = true;
}
}
}
#Override
public void characters(char[] ch,int start,int length) throws SAXException{
elementValue+= new String(ch,start,length).trim();
Log.i("CHARACTERS VALUE", ""+elementValue);
}
#Override
public void endElement(String Uri,String localName,String qName) throws SAXException
{
if(localName.equalsIgnoreCase(RecordElement)){
Records.add(newObj);
inProcess = false;
}
else if(inProcess){
ClassUtils.objectMapping(newObj, localName, elementValue);
}
}
}
AddAlbumDetailActivity.java
import android.util.Log;
public class AddAlbumDetailBean
{
public String data = null;
public String code = null;
public String photocount = null;
public String id = null;
public String title = null;
public String thumb = null;
public String url = null;
public AddAlbumDetailBean()
{
this("","","","","","","");
}
public AddAlbumDetailBean(String data,String code,String photocount,String id,String title,String thumb,String url)
{
this.data = data;
this.code = code;
this.photocount = photocount;
this.id = id;
this.title = title;
this.thumb = thumb;
this.url = url;
}
}
While using grid view it is not easy to Set the Image View. but you can do it by trick.
Take Button instead of the Image and set the Button Background for the Appropriate image.
After that u can able to set the Set the Button in grid view.
Thanks.
Related
NOTE :
First of all before writing any thing. this is not a duplicate because if it is then why I will post this here. I didn't find any of the stackoverflow similar questions' answers helpful to me at all for 2 days straight.
THE PROBLEM :
I have an activity that takes two fields of data and then go to the next activity where it has a view pager and the activity opens 2 fragments the posts and the profile. the problem here is that when I go back to the first activity to input different data and go to the fragments the listview shows duplicate data.
I tried every possible solution but none works.
I tried to clear adapter.
I tried to pass empty adapter.
I tried more things in the life cycle of the fragment but nothing.
so please I need help. thanks in advance.
package psychrating.psychrating;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/7/2017.
*/
public class PostsFragment extends Fragment {
static ListView posts_list;
Spinner list_order;
SearchView search;
String category, date, activity;
boolean get_data;
public static ArrayList<String> data = null;
static Context c;
transient ViewHolder holder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
data = null;
activity = getArguments().getString("activity");
category = getArguments().getString("category");
date = getArguments().getString("date");
if (activity == "main") {
// get_data = true;
}else {
// get_data = true;
}
View view = inflater.inflate(R.layout.post_tab, container, false);
init(view);
posts_list.clearChoices();
if (searchResultses != null) {
searchResultses.clear();
searchResultses = null;
}
return view;
}
private void init(View view) {
posts_list = (ListView) view.findViewById(R.id.posts_list);
list_order = (Spinner) view.findViewById(R.id.list_order);
search = (SearchView) view.findViewById(R.id.search);
posts_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
holder = (ViewHolder) view.getTag();
Temp temp = new Temp();
temp.name = holder.name.getText().toString();
temp.highest = holder.highest.getText().toString();
temp.dname = holder.dname.getText().toString();
temp.date = holder.date.getText().toString();
temp.category = holder.category;
temp.sdesc = holder.sdesc;
temp.ddesc = holder.ddesc;
Intent i = new Intent(c, ProfileActivity.class);
i.putExtra("holder", temp);
startActivity(i);
}
});
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
c = context;
}
#Override
public void onResume() {
super.onResume();
searchResultses = new ArrayList<>();
new Server(this.getActivity(), "posts").execute(category, date);
}
public static final String TAG ="ahmed";
static void removeCommas() {
StringBuilder word = new StringBuilder();
for (int i = 0; i < data.size(); i++) {
for (int j = 0; j < data.get(i).length(); j++) {
char c = data.get(i).charAt(j);
if (c != ',') {
word.append(c);
}else {
words.add(word.toString());
word.delete(0, word.length());
}
}
}
}
#Override
public void onPause() {
super.onPause();
searchResultses = null;
adapter = null;
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
static void addToClass() {
SearchResults s;
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}
static ArrayList<SearchResults> searchResultses = null;
static ArrayList<String> words = new ArrayList<>();
static MyCustomBaseAdapter adapter = null;
public static void fillList() {
removeCommas();
addToClass();
ArrayList<SearchResults> empty = new ArrayList<>();
adapter = new MyCustomBaseAdapter(c, empty);
adapter = new MyCustomBaseAdapter(c, searchResultses);
posts_list.setAdapter(adapter);
}
}
NOTE:
the fillList is a func that is being called by the asynctask when it finished retrieving data . which use the data variable and remove commas from data and add words to searchResult class
package psychrating.psychrating;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/10/2017.
*/
public class MyCustomBaseAdapter extends BaseAdapter {
private static ArrayList<SearchResults> searchArrayList = null;
private LayoutInflater mInflater;
public MyCustomBaseAdapter(Context context, ArrayList<SearchResults> results) {
super();
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(searchArrayList.get(position).getName());
holder.highest.setText(searchArrayList.get(position).getHighest());
holder.dname.setText(searchArrayList.get(position).getDName());
holder.date.setText(searchArrayList.get(position).getDate());
holder.category = searchArrayList.get(position).getCategory();
holder.sdesc = searchArrayList.get(position).getSdesc();
holder.ddesc = searchArrayList.get(position).getDdesc();
convertView.setTag(holder);
return convertView;
}
}
Server class
package psychrating.psychrating;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by Ahmeed on 8/6/2017.
*/
public class Server extends AsyncTask<String, String, String> {
private Context context;
private ProgressDialog progressDialog;
private AlertDialog.Builder builder;
private String type;
private static ArrayList<String> data = null;
Server(Context context, String type) {
this.context = context;
this.type = type;
}
private void createPreDialog(String message) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.setCancelable(false);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressDialog.create();
}
progressDialog.show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
createPreDialog("hold on");
}
#Override
protected String doInBackground(String... params) {
switch (type) {
case "login":
String personName = params[0];
String personEmail = params[1];
String id = params[2];
//
OutputStreamWriter outputStreamWriter = null;
BufferedWriter writer = null;
BufferedReader bufferedReader = null;
HttpURLConnection connection = null;
String line;
String result = null;
try {
URL url = new URL("http://192.168.1.64/blabla/sign_in.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setConnectTimeout(8000);
outputStreamWriter = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer = new BufferedWriter(outputStreamWriter);
String parameters = "name=" + personName + "&email=" + personEmail + "&id=" + id;
writer.write(parameters);
writer.flush();
if (connection.getResponseCode() == 200) {
bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
result = line;
}
} else {
result = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter != null) {
outputStreamWriter.close();
}
if (connection != null) {
connection.disconnect();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
case "posts":
String category = params[0];
String date = params[1];
//
OutputStreamWriter outputStreamWriter1 = null;
BufferedWriter writer1 = null;
BufferedReader bufferedReader1 = null;
HttpURLConnection connection1 = null;
String line1 = "";
String result1 = null;
try {
URL url1 = new URL("http://192.168.1.64/blabla/posts.php");
connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestMethod("POST");
connection1.setDoOutput(true);
connection1.setDoInput(true);
connection1.setConnectTimeout(8000);
outputStreamWriter1 = new OutputStreamWriter(connection1.getOutputStream(), "UTF-8");
writer1 = new BufferedWriter(outputStreamWriter1);
String parameters1 = "category="+category+"&date="+date;
writer1.write(parameters1);
writer1.flush();
data = new ArrayList<>();
if (connection1.getResponseCode() == 200) {
bufferedReader1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
while ((line1 = bufferedReader1.readLine()) != null) {
data.add(line1);
}
} else {
result1 = "Server Error";
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStreamWriter1 != null) {
outputStreamWriter1.close();
}
if (connection1 != null) {
connection1.disconnect();
}
if (bufferedReader1 != null) {
bufferedReader1.close();
}
if (writer1 != null) {
writer1.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result1;
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
switch (type) {
case "login":
switch (s) {
case "Connect Error":
createDialog(s);
break;
case "Done":
Toast.makeText(context, s, Toast.LENGTH_LONG).show();
MainActivity.updateUI(true);
break;
case "Already Exist":
MainActivity.updateUI(true);
break;
case "Server Error":
createDialog(s);
break;
}
break;
case "posts":
if (data != null) {
PostsFragment.data = data;
PostsFragment.fillList();
data = null;
}
}
}
private void createDialog(String message) {
builder = new AlertDialog.Builder(context);
builder.setTitle("Error");
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create();
builder.show();
}
}
Your words in PostsFragment.java makes you element duplicate, In removeCommas() method first clears the words and then add the values to the words from data.
try this. searchResultses.clear(); at the start of addToClass()
static void addToClass() {
SearchResults s;
searchResultses.clear();
int offset = 0;
for (int j = 0; j < words.size(); j += 8) {
Log.d(TAG, String.valueOf(words.size()));
s = new SearchResults();
for (int i = 0; i < 8; i++) {
offset = 1;
s.add(words.get(i * offset));
}
offset += 1;
s.init();
searchResultses.add(s);
}
}
very new to android and wondering how I can make this sample code return to where it left off instead of having to reload the pictures on returning to the screen. Right now when I exit the screen and return I have to start all over. I have read and trying to understand the Android documents but having trouble making this work or where to begin... thanks everyone!
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=fdd73dc07613841fbe325b5103d673b7&user_id=65005067#N08&per_page=25&format=json";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "fdd73dc07613841fbe325b5103d673b7";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
///////////////////////////////////////////////////
//activity life-cycle overrides
//onResume
#Override
public void onResume() {
super.onResume();
//Log.i("ZZ", thisActivityName + ":onResume");
tToast("onResume");
}
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
//onPause
#Override
public void onPause() {
//Log.i("ZZ", thisActivityName + ":onPause");
super.onPause();
tToast("onPause");
}
//activity life-cycle overrides
///////////////////////////////////////////////////
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Please Wait");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}
Write your activity so that it is aware of its current state.
In your onPause() method, save that state in any manner that you like. SharedPrefs, storage to a database, to a flat file, etc.
In your onResume() method, read that state and restore it.
Trying to store images in this Flickr gallery so when user leaves the activity and returns the images don't need to be loaded again... I have been reading about getSharedPreferences used in the onPause method to keep the images from being destroyed... only problem is I can't find any examples dealing with images only text fields and such...thanks for any help
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=fdd73dc07613841fbe325b5103d673b7&user_id=65005067#N08&per_page=25&format=json";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "fdd73dc07613841fbe325b5103d673b7";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
///////////////////////////////////////////////////
//activity life-cycle overrides
//onResume
#Override
public void onResume() {
super.onResume();
//Log.i("ZZ", thisActivityName + ":onResume");
tToast("onResume");
}
private void tToast(String s) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, s, duration);
toast.show();
}
//onPause
#Override
public void onPause() {
//Log.i("ZZ", thisActivityName + ":onPause");
super.onPause();
tToast("onPause");
}
//activity life-cycle overrides
///////////////////////////////////////////////////
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Please Wait");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}
I think what you need is image caching. Storing SharedPreferences comes with memory limitations. If the number of images is large, you can try this library for image caching:
Hope this helps !
I am hoping someine can help me figure out how to cache the Flickr Json images to cache for faster loading and offline use...the code below is from a tutorial and i have all that figured out but am lost with trying to read/use the Android developer resources and other example on the web...be very grateful for a solution and help making this work...I am new to programming and appreciate the knowledge here :)
package com.windmillagency;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidFlickrActivity extends BT_activity_base {
public String thisActivityName = "Flickr";
ProgressDialog progressDialog;
BackgroundThread backgroundThread;
public class FlickrImage {
String Id;
String Owner;
String Secret;
String Server;
String Farm;
String Title;
Bitmap FlickrBitmap;
FlickrImage(String _Id, String _Owner, String _Secret,
String _Server, String _Farm, String _Title){
Id = _Id;
Owner = _Owner;
Secret = _Secret;
Server = _Server;
Farm = _Farm;
Title = _Title;
FlickrBitmap = preloadBitmap();
}
private Bitmap preloadBitmap(){
Bitmap bm= null;
String FlickrPhotoPath =
"http://farm" + Farm + ".static.flickr.com/"
+ Server + "/" + Id + "_" + Secret + "_m.jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection
= (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
public Bitmap getBitmap(){
return FlickrBitmap;
}
}
class FlickrAdapter extends BaseAdapter{
private Context context;
private FlickrImage[] FlickrAdapterImage;;
FlickrAdapter(Context c, FlickrImage[] fImage){
context = c;
FlickrAdapterImage = fImage;
}
public int getCount() {
// TODO Auto-generated method stub
return FlickrAdapterImage.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return FlickrAdapterImage[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView image;
if (convertView == null) {
image = new ImageView(context);
image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setPadding(8, 8, 8, 8);
} else {
image = (ImageView) convertView;
}
image.setImageBitmap(FlickrAdapterImage[position].getBitmap());
return image;
}
}
FlickrImage[] myFlickrImage;
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://api.flickr.com/myflickrURL";
String FlickrQuery_per_page = "&per_page=10";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "xxxxxxxxxxxxxxxxxxx";
final String DEFAULT_SEARCH = "flickr";
EditText searchText;
Button searchButton;
Gallery photoBar;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.activityName = "AndroidFlickrActivity";
BT_debugger.showIt(activityName + ":onCreate");
//reference to base layout..
LinearLayout baseView = (LinearLayout)findViewById(R.id.baseView);
//setup background colors...
BT_viewUtilities.updateBackgroundColorsForScreen(this, this.screenData);
//setup background images..
if(backgroundImageWorkerThread == null){
backgroundImageWorkerThread = new BackgroundImageWorkerThread();
backgroundImageWorkerThread.start();
}
//setup navigation bar...
LinearLayout navBar = BT_viewUtilities.getNavBarForScreen(this, this.screenData);
if(navBar != null){
baseView.addView(navBar);
}
//inflate this screens layout file...
LayoutInflater vi = (LayoutInflater)thisActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View thisScreensView = vi.inflate(R.layout.flickr, null);
//add the view to the base view...
baseView.addView(thisScreensView);
searchText = (EditText)findViewById(R.id.searchtext);
searchText.setText(DEFAULT_SEARCH);
searchButton = (Button)findViewById(R.id.searchbutton);
photoBar = (Gallery)findViewById(R.id.photobar);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(AndroidFlickrActivity.this,
"Progress", "Wait!");
backgroundThread = new BackgroundThread();
backgroundThread.setRunning(true);
backgroundThread.start();
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
inputStream.close();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private FlickrImage[] ParseJSON(String json){
FlickrImage[] flickrImage = null;
bmFlickr = null;
String flickrId;
String flickrOwner;
String flickrSecret;
String flickrServer;
String flickrFarm;
String flickrTitle;
try {
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("photos");
JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
flickrImage = new FlickrImage[JsonArray_photo.length()];
for (int i = 0; i < JsonArray_photo.length(); i++){
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(i);
flickrId = FlickrPhoto.getString("id");
flickrOwner = FlickrPhoto.getString("owner");
flickrSecret = FlickrPhoto.getString("secret");
flickrServer = FlickrPhoto.getString("server");
flickrFarm = FlickrPhoto.getString("farm");
flickrTitle = FlickrPhoto.getString("title");
flickrImage[i] = new FlickrImage(flickrId, flickrOwner, flickrSecret,
flickrServer, flickrFarm, flickrTitle);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flickrImage;
}
public class BackgroundThread extends Thread{
volatile boolean running = false;
int cnt;
void setRunning(boolean b){
running = b;
cnt = 10;
}
#Override
public void run() {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
myFlickrImage = ParseJSON(searchResult);
handler.sendMessage(handler.obtainMessage());
}
}
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
progressDialog.dismiss();
photoBar.setAdapter(new FlickrAdapter(AndroidFlickrActivity.this, myFlickrImage));
Toast.makeText(AndroidFlickrActivity.this,
"Images Loaded", Toast.LENGTH_LONG).show();
}
};
}
I suggest you have a look at Universal Image Loader on github.
Universal Image Loader allows you to easily integrate asynchronous image loading, caching and rendering of images on Android in list, gallery and grid format. If you want to implement your own solution, reading the source for this project is a great way to start. It was written by Sergey Tarasevich and is licensed under the BSD 3-clause.
I am trying to read an RSS feed. I have tried many links using the code below and succeeded, but when I try with that link above I get a FileNotFoundException. What could cause this, and how do I fix my code?
EfficientAdapter class:
package com.xmlparse;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class EfficientAdapter extends BaseAdapter
{
private Activity activity;
private ArrayList<Post> data;
private static LayoutInflater inflater = null;
//public ImageLoader imageLoader;
ViewHolder holder;
EfficientAdapter(Activity a, ArrayList<Post> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader = new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
return data.toArray().length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView label;
public TextView addr;
public ImageView image;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.label = (TextView) vi.findViewById(R.id.title);
holder.addr = (TextView) vi.findViewById(R.id.details);
holder.image = (ImageView) vi.findViewById(R.id.thumb);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.label.setText(data.get(position).getTitle());
// holder.addr.setText(data.get(position).getPubDate());
holder.addr.setText(data.get(position).getDescription());
imageLoader.DisplayImage((data.get(position).getThumbnail()), activity,
holder.image, 72, 72);
URL url = null;
try {
url = new URL((data.get(position).getThumbnail()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStream content = null;
try {
content = (InputStream)url.getContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(content , "src");
Bitmap mIcon1 = null;
try {
mIcon1 =
BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
holder.image.setImageBitmap(Bitmap.createScaledBitmap(mIcon1, 72, 72, false));
return vi;
}
}
Post class:
package com.xmlparse;
public class Post {
private String title;
private String thumbnail;
private String url;
private String description;
private String pubDate;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThumbnail() {
return thumbnail;
}
public void setThumbnail(String thumbnail) {
this.thumbnail = thumbnail;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public void setDescription(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getPubDate() {
return pubDate;
}
}
xmlparsemain activity class:
package com.xmlparse;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class xmlparsemain extends Activity {
/** Called when the activity is first created. */
ListView lv1;
ProgressDialog ShowProgress;
public ArrayList<Post> PostList = new ArrayList<Post>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1 = (ListView) findViewById(R.id.listView1);
ShowProgress = ProgressDialog.show(xmlparsemain.this, "",
"Loading. Please wait...", true);
new loadingTask().execute("http://screenrant.com/mobile/movie-reviews-feed.php");
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(Intent.ACTION_VIEW).setData(Uri
.parse(PostList.get(position).getUrl()));
startActivity(intent);
}
});
}
class loadingTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
SAXHelper sh = null;
try {
sh = new SAXHelper(urls[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
sh.parseContent("");
return "";
}
protected void onPostExecute(String s) {
lv1.setAdapter(new EfficientAdapter(xmlparsemain.this, PostList));
ShowProgress.dismiss();
}
}
class SAXHelper {
public HashMap<String, String> userList = new HashMap<String, String>();
private URL url2;
public SAXHelper(String url1) throws MalformedURLException {
this.url2 = new URL(url1);
}
public RSSHandler parseContent(String parseContent) {
RSSHandler df = new RSSHandler();
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(df);
/* URLConnection con = url2.openConnection();
con.setConnectTimeout(20000);
InputSource is = new InputSource(new InputStreamReader(con.getInputStream()));
xr.parse(is);*/
xr.parse(new InputSource(url2.openStream()));
} catch (Exception e) {
e.printStackTrace();
}
return df;
}
}
class RSSHandler extends DefaultHandler {
private Post currentPost = new Post();
StringBuffer chars = new StringBuffer();
#Override
public void startElement(String uri, String localName, String qName,
Attributes atts) {
chars = new StringBuffer();
if (localName.equalsIgnoreCase("item")) {
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("title")
&& currentPost.getTitle() == null) {
currentPost.setTitle(chars.toString());
}
if (localName.equalsIgnoreCase("pubDate")
&& currentPost.getPubDate() == null) {
currentPost.setPubDate(chars.toString());
}
if (localName.equalsIgnoreCase("description")
&& currentPost.getDescription() == null) {
currentPost.setDescription(chars.toString());
}
if (localName.equalsIgnoreCase("thumbnail")
&& currentPost.getThumbnail() == null) {
currentPost.setThumbnail(chars.toString());
}
if (localName.equalsIgnoreCase("link")
&& currentPost.getUrl() == null) {
currentPost.setUrl(chars.toString());
}
if (localName.equalsIgnoreCase("item")) {
PostList.add(currentPost);
currentPost = new Post();
}
}
#Override
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
}
}
My logcat report:
02-29 15:20:44.183: W/System.err(2470): java.io.FileNotFoundException: http://screenrant.com/mobile/movie-news-feed.php
try using HTtpConnection instead of URLConnection, as follows:
InputStream callWebErvice(String serviceURL){
// http get client
HttpClient client=new DefaultHttpClient();
HttpGet getRequest=new HttpGet();
try {
// construct a URI object
getRequest.setURI(new URI(serviceURL));
} catch (URISyntaxException e) {
Log.e("URISyntaxException", e.toString());
}
// buffer reader to read the response
BufferedReader in=null;
// the service response
HttpResponse response=null;
try {
// execute the request
response = client.execute(getRequest);
} catch (ClientProtocolException e) {
Log.e("ClientProtocolException", e.toString());
} catch (IOException e) {
Log.e("IO exception", e.toString());
}
if(response!=null)
return response.getEntity().getContent();
else
return null;
}
and change line xr.parse(new InputSource(url2.openStream()));
to
xr.parse(new InputSource(callWebErvice(url2)));