What my program is currently doing , it searches in a database for
an ID(inputed by the user), and based on that it displays the title,
and the respective "picture.jpg"(which is just a string).
What I want to do, is I want to take the string(picture.jpg), and use
that to search on the server. So in the end it should be something
like:
http://192.168.1.254/images/picture.jpg. And it should also display the picture.
SecondActivity.java
This is how my whole code looks like:
package br.exemplozxingintegration;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText pastetext;
private ClipboardManager myClipboard;
private ClipData myClip;
private Button btn;
private EditText textView1;
private Button buttonGet;
private TextView textViewResult;
private ImageView ImageView1;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
pastetext = (EditText) findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.buttonPaste);
btn.performClick();
textView1 = (EditText) findViewById(R.id.textView1);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
Image = (ImageView) findViewById(R.id.imageView1);
buttonGet.setOnClickListener(this);
}
#SuppressLint("NewApi")
public void paste(View view) {
ClipData cp = myClipboard.getPrimaryClip();
ClipData.Item item = cp.getItemAt(0);
String text = item.getText().toString();
pastetext.setText(text);
Toast.makeText(getApplicationContext(), "Text Pasted",
Toast.LENGTH_SHORT).show();
}
private void getData() {
String qrcode = textView1.getText().toString().trim();
if (qrcode.equals("")) {
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+textView1.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String title="";
String image = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject androidData = result.getJSONObject(0);
title = androidData.getString(Config.KEY_TITLE);
image = androidData.getString(Config.KEY_IMAGE);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Title:\t" + title);//+"\nImagine :\t"+ image);
//int id = getResources().getIdentifier("http://192.168.1.254/2015/380panel/uploads/images/sm/"
+ image, null, null);
//ImageView1.setImageURI(id);
Picasso.with(this).load("http://192.168.1.254/2015/380panel/uploads/images/sm/"
+ image).into(ImageView1);
}
#Override
public void onClick(View v) {
getData();
} }
// }
Easy with Picasso Library:
http://square.github.io/picasso/
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso Library: http://square.github.io/picasso/
Add this to gradle file in dependency :
compile 'com.squareup.picasso:picasso:2.5.2'
After add this library, try loading image url like this.
Picasso.with(context).load("<Any Image URL>").into(imageView);
Hope it will help you !
Since you are alreadu using volley , no need to use Picasso.Volley provides you with a NetworkImageView.Simply replace your ImageView in xml with com.android.volley.toolbox.NetworkImageView and in code just use
NetworkImageView image = (NetworkImageView)findViewById(R.id.imageView);
image.setImageUrl("your url");
Related
I wanted to make a program that would output a image fron the internet by a link to the screen, but the image either appears as a cropped strip, or does not appear at all. I will be very grateful for you help
code
package com.example.myapplication2;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText s;
private TextView d;
private Button button1;
private URL link;
private InputStream j;
private Bitmap bitmap;
private ImageView image4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = findViewById(R.id.textView12);
s = findViewById(R.id.editText1);
button1 = findViewById(R.id.button1);
image4 = findViewById(R.id.imageView3);
}
#Override
protected void onResume() {
super.onResume();
}
public void onClickStart(View view){
new Thread(new Runnable() {
#Override
public void run() {
try {
link = new URL(s.getText().toString());
try {
j = (InputStream)link.getContent();
}
catch (IOException e){
d.setText("fail");
}
}
catch (MalformedURLException e){
d.setText("fail");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
bitmap = BitmapFactory.decodeStream(j);
image4.setImageBitmap(bitmap);
}
});
}
}).start();
}
}
enter image description here
enter image description here
It is possible in incorrect handling of the permission or file type, I would appreciate your help
I have an activity that fetches content from a JSON URL and displays the contents in a list view.
The contents include images, URL of the post, description etc. Each content item has its own URL.
I want to open it in another activity which has a WebView.
This is MainActivity.java
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
ListView listView;
private static final String JSON_URL = "https://gist.githubusercontent.com/radiotracer133/f9c5abf2c1fb403c4091ff7bc2ed8845/raw/78b956f078191c3f4b6c2c9c27f92da7ada2f7b4/example.json";
//the tutorial list where we will store all the tutorial objects after parsing json
List<Books> booksList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
booksList = new ArrayList<>();
//this method will fetch and parse the data
loadTutorialList();
}
private void loadTutorialList() {
//getting the progressbar
final ProgressBar progressBar = findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
//creating a string request to send request to the url
StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//hiding the progressbar after completion
progressBar.setVisibility(View.INVISIBLE);
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response);
//we have the array named tutorial inside the object
//so here we are getting that json array
JSONArray tutorialsArray = obj.getJSONArray("Books");
//now looping through all the elements of the json array
for (int i = 0; i < tutorialsArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject tutorialsObject = tutorialsArray.getJSONObject(i);
//creating a books object and giving them the values from json object
Books books = new Books(tutorialsObject.getString("Name"), tutorialsObject.getString("image"),tutorialsObject.getString("Author"), tutorialsObject.getString( "Name_url" ));
//adding the books to tutoriallist
booksList.add( books );
}
//creating custom adapter object
MyAdapter adapter = new MyAdapter( booksList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occur
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
This is MyAdapter.java
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
public class MyAdapter extends ArrayAdapter<Books> {
//the tutorial list that will be displayed
private List<Books> booksList;
private Bitmap bitmap;
private Context mCtx;
//here we are getting the tutoriallist and context
//so while creating the object of this adapter class we need to give tutoriallist and context
public MyAdapter(List<Books> booksList, Context mCtx) {
super(mCtx, R.layout.list_item, booksList );
this.booksList = booksList;
this.mCtx = mCtx;
}
//this method will return the list item
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//getting the layoutinflater
ViewHolder holder;
LayoutInflater inflater = LayoutInflater.from(mCtx);
convertView = inflater.inflate(R.layout.list_item, null, true);
holder = new ViewHolder();
//getting text views
holder.textViewName = convertView.findViewById(R.id.textViewName);
holder.textDescription = convertView.findViewById(R.id.textViewImageUrl);
holder.imageView = convertView.findViewById(R.id.imageView);
holder.detailsView = convertView.findViewById( R.id.detailsview );
convertView.setTag(holder);
//Getting the books for the specified position
Books books = booksList.get(position);
String imageUrl = books.getImageUrl();
String tutorialDescription = books.getDescription();
String tutorialTitle = books.getName();
String detailsTitle = books.getDetails();
holder.textViewName.setText(tutorialTitle);
holder.textDescription.setText(tutorialDescription);
holder.detailsView.setText( detailsTitle );
if (holder.imageView != null) {
/*-------------fatching image------------*/;
new ImageDownloaderTask(holder.imageView).execute(imageUrl);
}
holder.imageView.setImageBitmap(bitmap);
return convertView;
}
static class ViewHolder {
TextView textViewName;
TextView textDescription;
ImageView imageView;
TextView detailsView;
}
}
How can I implement OnclickListerner here to open WebView?
I am making my college news feed app using Firebase, in which there is a list of items having an image, title and description. I want that if a user clicks on the list item, it automatically downloads the PDF file related to that news. So in the future, if I want to add some more news, How can I add the PDF to that new item? , or if I want to replace the old PDF link to new PDF link then how I can do that ?. Basically, I want a control on the firebase database So that I can change anytime the PDF link in my database.
Main Activity:
package com.namy86.dtu_saforum;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Display;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.squareup.picasso.Picasso;
public class Main2Activity extends AppCompatActivity {
private RecyclerView mBloglist;
FirebaseDatabase database;
DatabaseReference mReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mBloglist=(RecyclerView) findViewById(R.id.blog);
mBloglist.setHasFixedSize(true);
mBloglist.setLayoutManager(new LinearLayoutManager(this));
database=FirebaseDatabase.getInstance();
mReference=database.getReference();
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerAdapter<ModelClass,BlogViewHolder> firebaseRecyclerAdapter=new
FirebaseRecyclerAdapter<ModelClass,BlogViewHolder>(ModelClass.class,R.layout.design_row,BlogViewHolder.class,mReference){
#Override
protected void populateViewHolder(BlogViewHolder viewHolder, ModelClass model,int position){
viewHolder.setTitle(model.getTitle());
viewHolder.setDesc(model.getDesc());
viewHolder.setImage(getApplicationContext(),model.getImage(),model.getFile());
}
};
mBloglist.setAdapter(firebaseRecyclerAdapter);
}
public class BlogViewHolder extends RecyclerView.ViewHolder{
View mView;
Context ctx;
TextView post,description;
DownloadManager dm;
ImageView postImage;
public BlogViewHolder(View itemView){
super(itemView);
mView=itemView;
// itemView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//// Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://dtu.ac.in/Web/notice/2017/dec/file1219.pdf"));
////
//// Intent browserChooserIntent=Intent.createChooser(browserIntent,"Choose Browser Of Your Choice");
//// view.getContext().startActivity(browserChooserIntent);
//
//// TextView post2=(TextView)mView.findViewById(R.id.titletext);
//// TextView description2=(TextView)mView.findViewById(R.id.titletext2);
//// ImageView postImage2=(ImageView)mView.findViewById(R.id.images);
////
//// post2.setText(String.valueOf(post));
//// description2.setText(String.valueOf(description));
//// Picasso.with(ctx).load(String.valueOf(postImage)).into(postImage2);
//
// dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
// Uri uri = Uri.parse("https://firebasestorage.googleapis.com/v0/b/fir-dtu.appspot.com/o/Kaushik%20and%20Kaushik.pdf?alt=media&token=45d80725-dd37-4825-8c7d-23b0dbd50d17");
// DownloadManager.Request request = new DownloadManager.Request(uri);
// request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//
// Long reference = dm.enqueue(request);
//
//
//
//
//
//
//
//
// }
// });
}
public void setTitle(String title){
TextView post=(TextView)mView.findViewById(R.id.titletext);
post.setText(title);
}
public void setDesc(String desc){
TextView description=(TextView)mView.findViewById(R.id.titletext2);
description.setText(desc);
}
public void setImage(Context ctx, String image, final String file){
ImageView postImage=(ImageView)mView.findViewById(R.id.images);
Picasso.with(ctx).load(image).into(postImage);
postImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(file);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = dm.enqueue(request);
}
});
}
}
}
I have this weird periodic error, when i boot the app, and the onCreate is called, but the CardView is not showing anything. Other times I do the exact same thing, booting the app, and the CardView is showing exactly what it should.
I can't seem to find the error..
The main class:
package lassebjoerklund.easyfridge;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class BootActivity extends Activity {
//TODO Make get method for table with barcode.
//TODO Update postRequest so that it macthes the barcode to the database, and getting a json object. object -> toString
private ArrayList<Products> productsToDisplayInlist;
private String TAG = BootActivity.class.getSimpleName();
private String getDataurl = "http://XXX.XXX.XXX.XXX/selectAll.php";
private static String insertDataUrl = "http://XXX.XXX.XXX.XXX/insertAll.php";
private JsonArrayRequest jsonArrayRequest;
private RecyclerView.Adapter mAdapter;
private String jsonRespons = "";
private static RequestQueue rQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boot_layout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.cardList);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
//RequestQueue
rQueue = Volley.newRequestQueue(this);
productsToDisplayInlist = new ArrayList<>();
getRequest();
Log.d(TAG, productsToDisplayInlist.toString());
mAdapter = new ProductCardAdapter(productsToDisplayInlist);
recyclerView.setAdapter(mAdapter);
//Intent to switch to activity
//final Intent dispalyProductsIntent = new Intent(BootActivity.this, ProductViewController.class);
//final Intent scanBarcodeIntent = new Intent(BootActivity.this, BarcodeTracking.class);
//final ImageButton updateViewButton = (ImageButton) findViewById(R.id.bViewProducts);
/*updateViewButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dispalyProductsIntent);
}
});*/
/* final ImageButton addNewEntry = (ImageButton) findViewById(R.id.addEntry);
addNewEntry.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
startActivity(scanBarcodeIntent);
}
});*/
}
#Override
protected void onResume() {
Log.d("onResume", "onResume");
/*Toast toast = Toast.makeText(this, "onResume", Toast.LENGTH_LONG);
toast.show();*/
super.onResume();
}
#Override
protected void onRestart() {
Log.d("onRestart", "onRestart");
/*Toast toast = Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT);
toast.show();*/
super.onRestart();
}
#Override
protected void onStop() {
Log.d("onStop", "onStop");
// productsToDisplayInlist.clear();
super.onStop();
}
#Override
protected void onPause() {
Log.d("onPause", "onPause");
super.onPause();
}
//TODO make error msg if there is no connection.
public void getRequest() {
productsToDisplayInlist.clear();
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getDataurl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject productToBuild = (JSONObject) response.get(i);
jsonRespons = productToBuild.toString();
String barcode = productToBuild.getString("code");
String name = productToBuild.getString("name");
String type = productToBuild.getString("type");
int id = productToBuild.optInt("id");
String rmDate = productToBuild.getString("rm_date");
String exDate = productToBuild.getString("ex_date");
String placementDate = productToBuild.getString("add_date");
Products product = new Products(barcode, name, placementDate, exDate, rmDate, type);
productsToDisplayInlist.add(product);
Log.d("Product", product.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volly", "Error");
error.printStackTrace();
}
});
rQueue.add(jsonArrayRequest);
}
public static void postRequest(final Products product) {
try {
StringRequest stringRequest = new StringRequest(Request.Method.POST, insertDataUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("onResponse", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley insertData", "ERROR");
Log.d("error: ", error.getCause().toString());
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> perameters = new HashMap<>();
perameters.put("barcode", product.getBarcode());
perameters.put("addDate", product.getDayOfadd());
perameters.put("exDate", product.getExDate());
return perameters;
}
};
rQueue.add(stringRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here I init the layout and add the adapter for the RecycleView. The productsToDisplayInList is populated in the getRequest() method. But somehow, it's only periodic getting populated..
Adapter class:
package lassebjoerklund.easyfridge;
import android.graphics.Color;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ProductCardAdapter extends RecyclerView.Adapter<ProductHolder> {
private CardView cardView;
private List<Products> productses;
private Calendar c;
public ProductCardAdapter(ArrayList<Products> items) {
productses = items;
}
#Override
public int getItemCount() {
return productses.size();
}
#Override
public void onBindViewHolder(ProductHolder holder, int position) {
Products product = productses.get(position);
Date returnDate = Util.parseDateString(product.getExDate());
if (Util.getCurrentDate().after(returnDate)) {
cardView.setCardBackgroundColor(Color.parseColor("#FF000D"));
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
} else {
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
}
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardlayout, parent, false);
cardView = new CardView(parent.getContext());
return new ProductHolder(itemView);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Holder Class:
package lassebjoerklund.easyfridge;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView cardName;
protected TextView cardAddDate;
protected TextView cardExDate;
protected TextView cardType;
public ProductHolder(View itemView) {
super(itemView);
cardName = (TextView) itemView.findViewById(R.id.cardName);
cardAddDate = (TextView) itemView.findViewById(R.id.cardAddDate);
cardExDate = (TextView) itemView.findViewById(R.id.cardExDate);
cardType = (TextView) itemView.findViewById(R.id.cardType);
}
}
I have an onClickListener that should call a class that shows and image from a static url. I put a toast in the called class and that shows but no image. The list.onClickListener should call the class ShowImage which should post an image. Please help I am not sure what I am doing incorrect.
Note* in my main_layout.xml I have an imageview.
package com.flash_tattoo;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
JSONArray jsonArray;
try {
jsonArray = new JSONArray(jsonData);
String[] mStrings = new String[jsonArray.length()];
String[] mImages = new String[jsonArray.length()];
String[] mPath = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings[i] = "http://www.2020mediaonline.com/tattoo/thumbnail_image/" + url;
String image_name = jsonArray.getJSONArray(i).getString(1);
mImages[i] = image_name;
String path_name = jsonArray.getJSONArray(i).getString(1);
mPath[i] = path_name;
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings, mImages);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
ShowImage go = new ShowImage();
Toast.makeText(MainActivity.this, "In onClick", Toast.LENGTH_LONG).show();
}
});
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ShowImage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
Drawable drawable = LoadImageFromWebOperations("http://www.ansi.okstate.edu/breeds/other/llama/llama1.jpg");
imgView.setImageDrawable(drawable);
Toast.makeText(MainActivity.this, "show big image", Toast.LENGTH_LONG).show();
}
private Drawable LoadImageFromWebOperations(String url)
{
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;
}
}
}
#Override
public void onDestroy()
{
adapter.imageLoader.stopThread();
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this,flash_tattoo.class);
startActivityForResult(myIntent, 0);
}
};
}
I suggest you to use AsyncTask to load your bitmap and populate it to your imageView, you can find more details via the following link:
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
Hope this can help you.
You can't use constructor to start new activity. You must use startActivity() for that. So I don't see why you expect ShowImage go = new ShowImage() to do anything. It's just an empty default constructor.
This is what you are looking for. Thanks.