loading images to a recyclerview using a thread - java

So I have a Recyclerview which holding items with images, I want to load images into the items but when I do that I got a lot of fps drops.
I read that I need to use another thread for the network part and I tried to do that as you can see, and it seems good to me but I can't figure out how to stop the fps drops and make the scrolling in the Recyclerview smooth, this Recyclerview supposed to hold between 10 and 100. Am I supposed to run the activity in a thread?
Note: The fps drops occur with 10 items.
calling to the HttpWrapper.LoadImageFromWebOperations function in OnBindViewHolder.
HomeAdapter.java
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeViewHolder>{
private Context context;
private ArrayList<RecipeModel> items;
public HomeAdapter(Context context, ArrayList<RecipeModel> items) {
this.context = context;
this.items = items;
}
#Override
public HomeAdapter.HomeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.home_item,null);
HomeAdapter.HomeViewHolder holder = new HomeAdapter.HomeViewHolder(v);
return holder;
}
public void addItem(RecipeModel item){
this.items.add(item);
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(HomeAdapter.HomeViewHolder holder, final int position) {
RecipeModel model = items.get(position);
holder.name.setText(model.getName());
holder.directions.setText(model.getDirections()[0]);
Drawable drawable = HttpWrapper.LoadImageFromWebOperations(model.getImageSource());
holder.image.setImageDrawable(drawable);
}
#Override
public int getItemCount() {
return items.size();
}
class HomeViewHolder extends RecyclerView.ViewHolder{
TextView name;
TextView directions;
ImageView image;
public HomeViewHolder(View itemView) {
super(itemView);
name = (TextView) itemView.findViewById(R.id.recipe_name);
directions = (TextView) itemView.findViewById(R.id.recipe_directions);
image = (ImageView) itemView.findViewById(R.id.recipe_image);
}
}
HttpWrapper.java
public class HttpWrapper {
String responseMsg = "";
private OkHttpClient client;
private Request request;
public static final String base_url = "http://kingtimmy.pythonanywhere.com";
public static final String home_route = "/home/";
public HttpWrapper() {
client = new OkHttpClient();
}
public ArrayList<RecipeModel> get_home_recipes(int recipe_num){
ArrayList<RecipeModel> models = new ArrayList<RecipeModel>();
request = new Request.Builder().url(base_url + home_route + String.valueOf(recipe_num)).build();
responseMsg = "";
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
responseMsg = "Error: " + e.getMessage();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
responseMsg = response.body().string();
}
});
while(responseMsg.equals("")){
continue;
}
String[] jsons = responseMsg.split("]-]");
for (int i = 0; i < jsons.length; i++){
models.add(makeRecipeModel(jsons[i]));
}
return models;
}
public RecipeModel makeRecipeModel(String msg){
JSONObject nodeRoot = null;
RecipeModel model;
try {
nodeRoot = new JSONObject(msg);
String[] directions = nodeRoot.get("directions").toString().split("\\n");
String[] ingredients = nodeRoot.get("ingredients").toString().split("\\n");
String image_source = nodeRoot.get("image").toString();
String source_url = nodeRoot.get("source_url").toString();
String name = nodeRoot.get("name").toString();
int id = Integer.valueOf(nodeRoot.get("id").toString());
model = new RecipeModel(directions,ingredients,image_source,source_url,name,id);
} catch (JSONException e) {
model = null;
}
return model;
}
public static Drawable LoadImageFromWebOperations(final String url) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<Drawable> callable = new Callable<Drawable>() {
#Override
public Drawable call() {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
System.out.println("Exc=" + e);
return null;
}
}
};
Future<Drawable> future = executor.submit(callable);
// future.get() returns 2 or raises an exception if the thread dies, so safer
try {
Drawable d = future.get();
executor.shutdown();
return d;
} catch (Exception e) {
return null;
}
}
What am I doing wrong?

Instead of writing your own thread and code to fetch, parse, decode and load the image, give Glide a try. It does all that for you with a simple single line code and loads the image in your ImageView

Related

Define text color based on value using AsyncTask

So basically my AsyncTask get the value from the url and when i execute i wanna show green text or red text if contains ("-").
I have search around and none of the option worked for me. i do have a RecyclerView.ViewHolder but don't know how to incorporate before i execute. Everything works, except the colors.
Thank you in advance
Activity
public class BTCData extends AsyncTask<Void,RecyclerView.ViewHolder,Void> {
String data = "";
String dataParsed1h ="";
String dataParsed24h ="";
String dataParsed7d ="";
String percent_change_1h = "";
String percent_change_24h = "";
String percent_change_7d = "";
Activity activity;
List<Model> items;
public BTCData() {
}
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL ("https://...");
HttpURLConnection httpURLConnection = (java.net.HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null){
line = bufferedReader.readLine();
data = data+line;
}
JSONArray JA = new JSONArray(data);
for(int i=0 ;i< JA.length(); i++){
JSONObject JO = (JSONObject) JA.get(i);
percent_change_1h = "1H " + JO.getString("percent_change_1h") + "%";
percent_change_24h = "24H " + JO.getString("percent_change_24h") + "%";
percent_change_7d = "7D " + JO.getString("percent_change_7d") + "%" ;
dataParsed1h = dataParsed1h + percent_change_1h;
dataParsed24h = dataParsed24h + percent_change_7d;
dataParsed7d = dataParsed7d + percent_change_24h;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.btc_percent_change_1h.setText(this.dataParsed1h);
MainActivity.btc_percent_change_24h.setText(this.dataParsed24h);
MainActivity.btc_percent_change_7d.setText(this.dataParsed7d);
}
}```
**View Holder**
public class CoinAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Adapter adapter;
boolean isLoading;
Activity activity;
List<Model> items;
int visibleThreshold = 5,lastVisibleItem, totalItemcount;
public void setAdapter(Adapter adapter) {
this.adapter = adapter;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(activity)
.inflate(R.layout.activity_main,parent,false);
return new CoinViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
Model item = items.get(position);
CoinViewHolder holderItem = (CoinViewHolder)holder;
holderItem.btc_percent_change_1h.setTextColor(item.getPercentage_change_1h().contains("-")?
Color.parseColor("#FF0000"):Color.parseColor("#32CD32"));
holderItem.btc_percent_change_24h.setTextColor(item.getPercentage_change_24h().contains("-")?
Color.parseColor("#FF0000"):Color.parseColor("#32CD32"));
holderItem.btc_percent_change_7d.setTextColor(item.getPercentage_change_7d().contains("-")?
Color.parseColor("#FF0000"):Color.parseColor("#32CD32"));
}
#Override
public int getItemCount() {
return items.size();
}
public void setLoader() {isLoading = true;}
public void updateData (List<Model> models)
{
this.items = models;
notifyDataSetChanged();
}
**on Activity**
public static TextView btc_percent_change_1h;
public static TextView btc_percent_change_24h;
public static TextView btc_percent_change_7d;
//Percentage
btc_percent_change_1h = (TextView) findViewById(R.id.btc_percent_change_1h);
btc_percent_change_24h = (TextView) findViewById(R.id.btc_percent_change_24h);
btc_percent_change_7d = (TextView) findViewById(R.id.btc_percent_change_7d);
and finally call...
BTCData process = new BTCData();
process.execute();
This is because for setting color you are doing in onBindViewHolder when in that case data would be 0 only without red sign and later you are setting data but after that onBindViewHolder is not called and hence changes are not reflecting.
The way you are doing all this is not ideal way and would suggest you to read design patterns to implement it in proper way.
Maybe is not the best option, but it works
#Override
protected void onPostExecute(CoinAdapter aVoid) {
super.onPostExecute(aVoid);
MainActivity.btc_percent_change_1h.setTextColor((this.dataParsed1h.contains("-")?
Color.parseColor("#FF0000"):Color.parseColor("#32CD32")));
MainActivity.btc_percent_change_1h.setText(this.dataParsed1h);
MainActivity.btc_percent_change_24h.setTextColor((this.dataParsed24h.contains("-")?
Color.parseColor("#FF0000"):Color.parseColor("#32CD32")));
MainActivity.btc_percent_change_24h.setText(this.dataParsed24h);
MainActivity.btc_percent_change_7d.setTextColor((this.dataParsed7d.contains("-")?
Color.parseColor("#FF0000"):Color.parseColor("#32CD32")));
MainActivity.btc_percent_change_7d.setText(this.dataParsed7d);
}
You can achieve it like. Get value in adapter according to position and change it color like this. Then cocatinate both string and show it. You can test it on multiple devices it will run and show exact in every devices.
String status = getColoredSpanned(act.getResources().getString(R.string.order_status),"#3EA7BD");
String variable_status =getColoredSpanned(act.getResources().getString(R.string.status_order_pending),"#E23941");
String text = status+variable_status;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
myViewHolder.tv_order_product_status.setText(Html.fromHtml(text, Html.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE);
} else {
myViewHolder.tv_order_product_status.setText(Html.fromHtml(text), TextView.BufferType.SPANNABLE);
}

ViewPager Not getting Images from server

I am using ViewPager in my app and fetch the data(Images) from server(with JSON). Even if runs smoothly no image is shown in the viewpager.
I read so many tutorial regarding this, but nobody solve my problem. Please tell me where i am wrong...
Here is my code:
view_pager.xml
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="40dp" />
image_view.xml
<ImageView
android:id="#+id/image_adapter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"/>
ViewPager_Adapter.java
public class ViewPager_Adapter extends PagerAdapter {
private String urls;
private LayoutInflater inflater;
private Context context;
ArrayList<String> mylist;
public ViewPager_Adapter(Context context, ArrayList<String> mylist) {
this.context = context;
this.urls = urls;
this.mylist = mylist;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return mylist.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.image_view, null);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image_adapter);
Glide.with(context)
.load(mylist.get(position))
.into(imageView);
view.addView(imageLayout,0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
View_Pager.Java
public class View_Pager extends Fragment {
private static ViewPager mPager;
JSONArray responsearray = null;
String imageOne;
private static final String TAG_PHOTO_ONE = "Gallery_Full";
ArrayList<String> myList;
HashMap<String, String> get;
ViewPager_Adapter viewpager_adapter;
LinearLayout addimages;
int REQUEST_CODE = 100;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.view_pager, null);
mPager = view.findViewById(R.id.viewpager);
new GetImages().execute(true);
return view;
}
class GetImages extends AsyncTask<Boolean, Void, String> {
#Override
protected String doInBackground(Boolean... booleans) {
ImageApi imageApi = new ImageApi();
String result = null;
try {
result = imageApi.galleryget(sharedPreferences.getString("id", ""));
JSONObject object = new JSONObject(result);
if (object.getString("error").equalsIgnoreCase("false")) {
responsearray = object.getJSONArray("response");
return "true";
} else {
String errormsg = object.getString(result);
return errormsg;
}
} catch (ApiException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
if (s.equalsIgnoreCase("true")) {
showList(responsearray);
}
}
}
}
public void showList(final JSONArray responsearray) {
try {
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>();
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
}
Use this code for showList() as you are not populating you're arrayList properly the data is being over write in one position .
So , what you have to do is initialize it out side of for loop .
public void showList(final JSONArray responsearray) {
try {
//here
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(String.valueOf(get));
}
viewpager_adapter = new ViewPager_Adapter(getActivity(), myList);
String test = String.valueOf(myList);
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + imageOne;
Log.e("FINALPATH", finalimgpath);
} catch (JSONException e) {
e.printStackTrace();
}
mPager.setAdapter(viewpager_adapter);
viewpager_adapter.notifyDataSetChanged();
}
Edit
Also if your final image path is as below then you have to update your code in adapter for image path as follow.
Update position in view.addView() too.
String test = String.valueOf(mylist.get(position));
String imgpath = getString(R.string.imgpath);
String finalimgpath = imgpath + test;
Glide.with(context)
.load(finalimgpath)
.into(imageView);
view.addView(imageLayout,position);
return imageLayout;
In your For loop you are initialising your list everytime
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList = new ArrayList<>(); // THIS IS WRONG. don't initialise every time
myList.add(String.valueOf(get)); // THIS IS ALSO WRONG. you are adding hashmap object to list
}
So make your for loop like this
myList = new ArrayList<>();
for (int i = 0; i < responsearray.length(); i++) {
JSONObject responseObject = responsearray.getJSONObject(i);
Log.e("COUNT" + i, String.valueOf(responseObject));
imageOne = responseObject.getString(TAG_PHOTO_ONE);
get = new HashMap<>();
get.put(TAG_PHOTO_ONE, imageOne);
myList.add(imageOne);
}

asynctask with callback - cant display images

Cannot display images.. unless putting the adding code in the callback function. But because i ve to cycle draw operation, ive just used the assignment
imageHandler = image; it seems to not work
activity class:
public class Home extends ActionBarActivity implements OnTaskComplete{
public Bitmap imageHandler;
#Override
public void callBackFunction(Bitmap image) {
imageHandler = image;
}
public class Post{
String id;
String title;
String description;
String release;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getRelease() {
return release;
}
public void setTitle(String title) {
this.title = title;
}
public void setDescription(String description) {
this.description = description;
}
public void setRelease(String release) {
this.release = release;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Context context = this;
String result = null;
ArrayList<Post> focusOn = new ArrayList<Post>();
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLDataReader reader = new URLDataReader(context);
result = reader.execute(address).get();
}catch (IOException e){
e.printStackTrace();
} catch(InterruptedException e){
e.printStackTrace();
} catch (ExecutionException e){
e.printStackTrace();
}
try {
JSONObject obj = new JSONObject(result);
String success = (String) obj.getString("success");
JSONArray records = obj.getJSONArray("records");
for(int i = 0; i < records.length(); i++) {
Post tmp = new Post();
tmp.setId(records.getJSONObject(i).getString("id"));
tmp.setTitle(records.getJSONObject(i).getString("title"));
tmp.setDescription(records.getJSONObject(i).getString("contents"));
tmp.setRelease(records.getJSONObject(i).getString("data_post"));
focusOn.add(tmp);
}
}catch (JSONException e){
e.printStackTrace();
}
//wrapper
LinearLayout container = (LinearLayout)findViewById(R.id.wrapper);
for(int i = 0; i < focusOn.size(); i++){
//item
LinearLayout item = new LinearLayout(getApplicationContext());
container.addView(item);
item.setOrientation(LinearLayout.HORIZONTAL);
//image
//Bitmap imageHandler = null;
URL address = null;
try {
address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/"+focusOn.get(i).getId()+"_thumb2.jpg");
URLImageReader reader = new URLImageReader(context,this);
reader.execute(address);
}catch(MalformedURLException e){
e.printStackTrace();
}
ImageView asset = new ImageView(getApplicationContext());
asset.setImageBitmap(imageHandler);
//Toast.makeText(getApplicationContext(),asset.toString(),Toast.LENGTH_LONG).show();
item.addView(asset);
LinearLayout.LayoutParams imgSettings = new LinearLayout.LayoutParams(300,300);
asset.setLayoutParams(imgSettings);
//inside
LinearLayout contents = new LinearLayout(getApplicationContext());
contents.setOrientation(LinearLayout.VERTICAL);
item.addView(contents);
//title
TextView title = new TextView(getApplicationContext());
title.setText(focusOn.get(i).getTitle());
title.setTextAppearance(this, R.style.title);
contents.addView(title);
//description
TextView description = new TextView(getApplicationContext());
description.setText(focusOn.get(i).getDescription());
description.setTextAppearance(this, R.style.description);
contents.addView(description);
//date
TextView date = new TextView(getApplicationContext());
date.setText(focusOn.get(i).getRelease());
date.setTextAppearance(this, R.style.description);
contents.addView(date);
}
}
}
URLImageReader Asynctask
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
Context context = null;
private OnTaskComplete mlistener;
public URLImageReader(Context context, OnTaskComplete mlistener){
this.context = context;
this.mlistener = mlistener;
}
#Override
protected Bitmap doInBackground(URL... params) {
Bitmap image = null;
try {
URL url= params[0];
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e){
e.printStackTrace();
}
return image;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
mlistener.callBackFunction(bitmap);
}
interface:
public interface OnTaskComplete{
void callBackFunction(Bitmap image);
}
You on task complete interface seems extraneous, just pass the imageview to it instead:
public class URLImageReader extends AsyncTask<URL, Void, Bitmap> {
private final Context context;
private final ImageView mImageView;
public URLImageReader(ImageView imageView){
this.context = imageView.getContext();
this.mImageView = imageView;
}
#Override
protected Bitmap doInBackground(URL... params) {
Bitmap image = null;
try {
URL url= params[0];
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e){
e.printStackTrace();
}
return image;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
if (mImageView != null){
mImageView.setImageBitmap(bitmap);
}
}
}
Then to call it,
// see final notes below about using this (the activity), lets create the imageview before we call URLImageReader constructor
ImageView asset = new ImageView(this);
try {
address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/"+focusOn.get(i).getId()+"_thumb2.jpg");
URLImageReader reader = new URLImageReader(asset);
reader.execute(address);
}catch(MalformedURLException e){
e.printStackTrace();
}
Also, don't use the application context to create views, use the Activity context instead.

Listview With Asynctask get no response from server

I want to send Cus_id from postParamName to web server.
According to cus_id I want to fetch data from server and get it into listview.
I have no error in my code...but the code still not able to fetch data from server..
Plz look at my code...i have been working on this code since last two days. but I am not able to find the mistake
Point1.java
public class Points1 extends ListActivity implements FetchDataListener {
SessionManager session;
TextView tvCusPoints1, tvCusPoints2, tvcusName;
TextView bus_name;
TextView cus_points;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.points);
initView();
}
private void initView() {
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// ID
String cus_id = user.get(SessionManager.KEY_ID);
ArrayList<NameValuePair> postParamName = new ArrayList<NameValuePair>();
postParamName.add(new BasicNameValuePair("cus_id", cus_id));
String url = "http://10.0.2.2/android_api_main/business_points.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
}
}
Application.java
public class Application
{
private String bus_name;
private String cus_points;
public String getbus_name() {
return bus_name;
}
public void setbus_name(String bus_name) {
this.bus_name = bus_name;
}
public String getcus_points() {
return cus_points;
}
public void setcus_points(String cus_points) {
this.cus_points = cus_points;
}
}
ApplicationAdapter.java
public class ApplicationAdapter extends ArrayAdapter<Application> {
private List<Application> items;
public ApplicationAdapter(Context context, List<Application> items) {
super(context, R.layout.point_list_item, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.point_list_item, null);
}
Application app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.item_bname1);
TextView dlText = (TextView) v.findViewById(R.id.item_bpoint1);
if (titleText != null)
titleText.setText(app.getbus_name());
if (dlText != null)
dlText.setText(app.getcus_points());
}
return v;
}
}
FetchDataTask.java
public class FetchDataTask extends AsyncTask<String, Void, String> {
private final FetchDataListener listener;
private String msg;
String cus_id, responseString, success, bus_name, cus_points;
SessionManager session;
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
if (params == null)
return null;
// get url from params
String url = params[0];
try {
// create http connection
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
// connect
HttpResponse response = client.execute(httpget);
// get response
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity);
// get response content and convert it to json string
} catch (IOException e) {
msg = "No Network Connection";
}
return responseString;
}
#Override
protected void onPostExecute(String sJson) {
try {
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
List<Application> apps = new ArrayList<Application>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
bus_name = json_data.getString("bus_name");
cus_points = json_data.getString("cus_points");
success = json_data.getString("success");
Application app = new Application();
app.setbus_name(json.getString("bus_name"));
app.setcus_points(json.getString("cus_points"));
// add the app to apps
apps.add(app);
}
if (listener != null)
listener.onFetchComplete(apps);
} catch (JSONException e) {
msg = "Invalid response";
if (listener != null)
listener.onFetchFailure(msg);
return;
}
}
}
FetchDataListener.java
public interface FetchDataListener {
public void onFetchComplete(List<Application> data);
public void onFetchFailure(String msg);
}
Your FetchDataTask constructor accepts FetchDataTaskListener as parameter
public FetchDataTask(FetchDataListener listener) {
this.listener = listener;
}
But you have initialized it using activity's context
FetchDataTask task = new FetchDataTask(this);
Could you please check this.
You should set listener correctly, something like this
this.mListener = (FetchDataListener) activity

How can a user import images into the app?

I'm editing an open source app: A simple coloring page app for kids. I need to be able to make the user import his own images to be colored. Here is the full source code.
And here is the code for loading images from R.drawable:
public class StartNewActivity extends NoTitleActivity implements View.OnClickListener
{
// This is an expensive operation.
public static int randomOutlineId()
{
return new ResourceLoader().randomOutlineId();
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Apparently this cannot be set from the style.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.start_new);
GridView gridview = (GridView) findViewById(R.id.start_new_grid);
gridview.setAdapter(new ImageAdapter(this));
}
public void onClick(View view)
{
setResult(view.getId());
finish();
}
private static class ResourceLoader
{
ResourceLoader()
{
// Use reflection to list resource ids of thumbnails and outline
// images.First, we list all the drawables starting with the proper
// prefixes into 2 maps.
Map<String, Integer> outlineMap = new TreeMap<String, Integer>();
Map<String, Integer> thumbMap = new TreeMap<String, Integer>();
Field[] drawables = R.drawable.class.getDeclaredFields();
for (int i = 0; i < drawables.length; i++)
{
String name = drawables[i].getName();
try
{
if (name.startsWith(PREFIX_OUTLINE))
{
outlineMap.put(name.substring(PREFIX_OUTLINE.length()),
drawables[i].getInt(null));
}
if (name.startsWith(PREFIX_THUMB))
{
thumbMap.put(name.substring(PREFIX_THUMB.length()),
drawables[i].getInt(null));
}
}
catch (IllegalAccessException e)
{
}
}
Set<String> keys = outlineMap.keySet();
keys.retainAll(thumbMap.keySet());
_outlineIds = new Integer[keys.size()];
_thumbIds = new Integer[keys.size()];
int j = 0;
Iterator<String> i = keys.iterator();
while (i.hasNext())
{
String key = i.next();
_outlineIds[j] = outlineMap.get(key);
_thumbIds[j] = thumbMap.get(key);
j++;
}
}
public Integer[] getThumbIds()
{
return _thumbIds;
}
public Integer[] getOutlineIds()
{
return _outlineIds;
}
public int randomOutlineId()
{
return _outlineIds[new Random().nextInt(_outlineIds.length)];
}
private static final String PREFIX_OUTLINE = "outline";
private static final String PREFIX_THUMB = "thumb";
private Integer[] _thumbIds;
private Integer[] _outlineIds;
}
private class ImageAdapter extends BaseAdapter
{
ImageAdapter(Context c)
{
_context = c;
_resourceLoader = new ResourceLoader();
}
public int getCount()
{
return _resourceLoader.getThumbIds().length;
}
public Object getItem(int i)
{
return null;
}
public long getItemId(int i)
{
return 0;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null)
{
// If it's not recycled, initialize some attributes
imageView = new ImageView(_context);
imageView.setLayoutParams(new GridView.LayoutParams(145, 145));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setOnClickListener(StartNewActivity.this);
}
else
{
imageView = (ImageView) convertView;
}
imageView.setImageResource(_resourceLoader.getThumbIds()[position]);
imageView.setId(_resourceLoader.getOutlineIds()[position]);
return imageView;
}
private Context _context;
private ResourceLoader _resourceLoader;
}
}
You can use File to write the imported file of the user. Use something like this.
public boolean write(byte[] data, File file)
{
if (file.getParentFile().exists()) {
if (file.exists()) {
file.delete();
}
} else {
file.getParentFile().mkdirs();
}
try{
OutputStream output = new FileOutputStream(file);
output.write(data);
output.close();
return true;
}catch(Exception e){
Log.v("FileManager", "Error writing file.", e);
return false;
}
}
Sample:
String pathName = "/mnt/sdcard/Android/data/com.company.project/files/tmp/photo.png";
Bitmap bmp = BitmapFactory.decodeFile(pathName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
write(byteArray, new File("/mnt/sdcard/Android/data/com.company.project/files/photo.png");

Categories