How to create image from webService, Android - java

So, I have this app that is connected to a WebService and I am already retrieving data from there, now I want to retrieve a image link and make that the imageView gets that image trough the link. Is that even possible? Appreciate any help :D
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
System.out.println(jsonObject1.optString("Designacao"));
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String URL_IMAGEM = "http://something.something.pt" + URL_IMAGE_SMALL;
new DownloadImage(imageView6).execute(URL_IMAGEM);
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
listaPaises.add(pais);
}
}
System.out.println(jsonObject.optString("Designacao"));
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
{...}
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (ImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

You can use Picasso, a wonderful image library.
Example:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Add dependency via Gradle:
compile 'com.squareup.picasso:picasso:2.5.2'

you can use any third party library
example use Glide library
this library will help you to fetch and display image on ImageView from url.
example:
Glide.with(context).load(image_url).into(your_image_view);
here is link for that library : https://github.com/bumptech/glide

You have to set your ImageView inside your XML as you normally do. Then you can use any third party library like Picasso or Glide that will load the image from the url and set it to your ImageView in your activity/fragment.

In your app build.gradle add
compile 'com.github.bumptech.glide:glide:3.7.0'
use this code to load image from url
Glide.with(getApplicationContext()).load("image_url").into(ImageView);

try this if you dont want to use third party library
new DownloadImage(imamgeview).execute(url);
create a Async Task
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
i hope you it will work in your case

step 1: create class named DownloadImage
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
CircleImageView bmImage;
public DownloadImage(ImageView bmImage) {
this.bmImage = (CircleImageView) bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Step 2: execute AsyncTask
new DownloadImage(imgUserProfile).execute(userProfileUrl);
**Json Url like this: ** https://graph.facebook.com/1220130444748799/picture?height=400&width=400&migration_overrides=%7Boctober_2012%3Atrue%7D

Related

Loading photos with basic auth

I have a code like this:
public class MainActivity extends AppCompatActivity {
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = findViewById(R.id.img1);
}
public void onClick(View v) {
new DownloadImageTask((ImageView) findViewById(R.id.img1))
.execute("http://view:view#178.217.49.11:5022/tmpfs/snap.jpg\"");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
It loads the photo fine from this link: http://92.63.192.191/d/SCP-1017.png, but it doesn't load the photo from here: http://view:view#178.217.49.11:5022/tmpfs/snap.jpg
UPDATE
I realized that I need to use basic auth, but I don't know how to do it.
UPDATE2
I did it! Here's my resulting class:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
URL url = new URL(urls[0]);
URLConnection uc = url.openConnection();
String userpass = USERNAME + ":" + PASSWORD;
String basicAuth = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
}
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
URL url = new URL(urls[0]);
URLConnection uc = url.openConnection();
String userpass = USERNAME + ":" + PASSWORD;
String basicAuth = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
}
uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}

How to get data from sqlite, and show it using stackwidget?

I want to retrieve url image from sqlite, then convert it to bitmap and show it into stackwidget. When insert url image manually, one by one, it works well. But when i use url image from sqlite, application is force close and my stackwidget doesn't show image.
public class StackRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory {
...
StackRemoteViewsFactory(Context context) {
mContext = context;
}
#Override
public void onCreate() {
FilmHelper filmHelper = FilmHelper.getInstance(mContext);
filmHelper.open();
}
#Override
public void onDataSetChanged() {
DatabaseHelper databaseHelper;
databaseHelper = new DatabaseHelper(mContext);
SQLiteDatabase databases = databaseHelper.getReadableDatabase();
long count = DatabaseUtils.queryNumEntries(databases, "note");
ArrayList<Film> ini = new ArrayList<>();
Cursor c =FilmHelper.database.rawQuery("SELECT * FROM note" , null );
c.moveToFirst();
Film note;
int i;
if (c.getCount() > 0) {
for (i=0; i < count; i++ ) {
do {
note = new Film();
note.setId(c.getInt(c.getColumnIndexOrThrow(_ID)));
note.setPosterPath(c.getString(c.getColumnIndexOrThrow(IMAGE)));
ini.add(note);
try {
URL url = new URL("https://image.tmdb.org/t/p/w600_and_h900_bestv2/" +
ini.get(i).getPosterPath());
Bitmap image = BitmapFactory.decodeStream(url.openStream());
mWidgetItems.add(image);
} catch (IOException e) {
System.out.println(e);
}
c.moveToNext();
} while (!c.isAfterLast());
}
}
c.close();
databases.close();
...
}
you are doing network consuming task like converting url to bitmap inside forloop in main thread.
you can use Asynctask that will download bitmap from url to you in onPostExecute and from that you can add bitmap to mWidgetItems.
class ConvertUrltoBitmap extends AsyncTask<String, Void, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public Bitmap doInBackground(String... urls) {
Bitmap map = null;
try {
URL url = new URL(urls[0]);
HttpURLConnection connection =(HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
map= BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
protected void onPostExecute(Bitmap bitmap){
try {
mWidgetItems.add(bitmap);
}catch (Exception exception){
exception.printStackTrace();
}
}}

How to acces TextView From another class

I've got my main startup class loading MainActivity but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.
private class DateValidation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog
}
#Override
protected String doInBackground(String... arg0) {
String hallId = arg0[0];
String date = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?id=" + URLEncoder.encode(hallId, "UTF-8");
data += "&date=" + URLEncoder.encode(date, "UTF-8");
link = "https://www.adoetech.co.tz/ehall/frontend/index.php/hall/validate-date" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
Log.d("postData: ", link);
return result;
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
boolean query_result = jsonObj.getBoolean("success");
String response = jsonObj.getString("data");
if (query_result) {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_LONG).show();
} else if (!query_result) {
Log.d("onPostExecute: ", "free");
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
//JSONArray dateVal = jsonObj.getJSONArray("data");
I need to setTest from here and I have declear hallPrice from MainActivity help Please
hallPrice.setText("300000000");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("onPostExecute: ", String.valueOf(result));
Toast.makeText(HallsDetails.this, "Error parsing JSON data.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HallsDetails.this, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Use intent to pass data from one activity to another like this:-
Intent in = new Intent(MainActivity.this, DateValidation.class);
in.putExtra("key", "300000000");
startActivity(in);
And in your DateValidation Activity do:-
Intent i = getIntent();
String value = i.getStringExtra("key");
hallPrice.setText(value);
You can pass the TextView in your AsyncTask.
public class DateValidation extends AsyncTask<String,String,String> {
TextView mTextView;
public DateValidation (TextView textView){
mTextView = textView;
}
#Override
protected String doInBackground(String... strings) {
/**
* do process here
*/
return "Result String here";
}
#Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}

Saving a URL to internal storage

So the title slightly misleading. I've put the URl in a drawable.
public Drawable getDrawableFromURL(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
I had it has a bitmap originally but kept getting nullpointers and android.os.NetworkOnMainThreadException, which I've managed to fix, but the nullpointer comes around again. So I'm stuck on how to save to internal, because I can save it to SD fine.
Thanks
try this
public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
// save your bitmap here
}
}
to call this AsyncTask use below code
new DownloadImage().execute(url);

Load an image from URL database

First code:
`db_img = Jasonobject.getString("image");
imagelink.setText(db_img);`
The code above is grab the data from mysql database.
"imagelink" is textview.
The code will display the data into textview
"image"from mysql is string because is url link.
Second code:
new DownloadImageTask((ImageView) findViewById(R.id.qrimg)).
execute("http://localhost/project/image/pic1.jpg");
The second code is load the image base on the URL
My problem is how to pass the value from first code into .execute("HERE")
Code:
`
EditText etacode;
EditText txtName;
Button btnscanitem;
//testing
TextView imagelink;
//hidden textview
TextView texttime;
TextView textunit;
TextView textrm;
TextView textexp;
Button btnconfrim;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.acode);
btnscanitem = (Button) findViewById(R.id.btnscanitem);
etacode = (EditText) findViewById(R.id.etacode);
etacode.setVisibility(View.GONE);
//testing
imagelink = (TextView) findViewById(R.id.imagelink);
btnconfrim = (Button) findViewById(R.id.btnconfrim);
btnconfrim.setVisibility(View.GONE);
img = (ImageView) findViewById(R.id.img);
img.setVisibility(View.GONE);
img.setImageResource(0);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(AcodeActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://Localhost/getproduct.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// Fetch data from Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String apromoid = Jasonobject.getString("aid");
String db_img="";
if(etcode.getText().toString().equalsIgnoreCase(apromoid)) {
db_img = Jasonobject.getString("image");
imagelink.setText(db_img);
String temp;
temp = db_img;
//String imagelink = temp;
//(db_img);
break;
}
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.acodescanner, menu);
return true;
}
public void onClick (View view){
if(view.getId() == R.id.btnscanitem){
IntentIntegrator integrator = new IntentIntegrator(this);
integrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
String acode;
acode = scanResult.getContents();
EditText etacode = (EditText) findViewById(R.id.etacode);
etacode.setText(acode);
new task().execute();
//String textlink = getimagelink;
new DownloadImageTask((ImageView) findViewById(R.id.qrimg))
.execute(db_img);
}
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
`

Categories