Getting the url of an image with jsoup - java

I am using google image search to look for images and get the URL of the first image in my android application using JSOUP library
My problem is that no matter how much I try It shows me that the URL is null
looks like the element that contains the first image does not have a url
here is the XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="arb.myapplication.MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_alignParentBottom="true"
android:layout_marginBottom="131dp"
android:id="#+id/imageView" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="39dp"
android:layout_marginEnd="39dp"
android:layout_marginTop="11dp"
android:id="#+id/button3"
android:elevation="0dp" />
Ignore the image view
I use the button to get the url of the image
here is the JAVA file
package arb.myapplication;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Attributes;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
class DownloadIcon extends AsyncTask<Object, Object, Integer>
{
#Override
protected Integer doInBackground(Object... objects) {
Connection connecion= Jsoup.connect("http://www.google.com/search?tbm=isch&q=facebook+logo");
try {
Document document=connecion.get();
Elements element=document.select("img.rg_ic.rg_i");
String url=element.first().absUrl("src");
publishProgress(url);
} catch (IOException e1) {
publishProgress(-1);
}
return 0;
}
#Override
protected void onProgressUpdate(Object... values) {
/* ImageView imageView=(ImageView) findViewById(R.id.imageView);
try {
InputStream inputStream= new URL(values[0].toString()).openStream();
imageView.setImageBitmap(BitmapFactory.decodeStream(inputStream));
} catch (IOException e) {
throw new RuntimeException(e);
}*/
Toast.makeText(getBaseContext(),values[0].toString(),Toast.LENGTH_LONG).show();
}
#Override
protected void onPostExecute(Integer integer) {
Toast.makeText(getBaseContext(),"done",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button3=(Button) findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DownloadIcon().execute();
}
});
}
}
in the onProgressUpdate function does not show the Toast because its text is null
I already tried to get the attribute keys and values of the chosen element
It matches those displayed when I parse the element using the Chrome explorer but without src attribute

The text is null because you get no images. If you debug your request you'll see 403 status code which tells you that Jsoup client is not authorized to fetch images from Google. You need to use or emulate browser to achieve your goal.

Related

Loading Json data won't show

I am trying to make an app that takes data from google sheet in JSON format.
I have tried a couple of different codes to make the data simply apeare on the screen, but could not make this happen.
would be glad for ideas.
tried with a several codes using AsyncTask and saw it is not working. so tried a
different approach..
the following app is a blank page with a button, that when you click it , it suppose to make name list apear on the screen.
the JSON url:
https://myjson.dit.upm.es/api/bins/1anx
the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="click me!"
android:layout_centerHorizontal="true"
android:layout_margin="50dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginHorizontal="150dp"
android:padding="5dp"
android:textSize="24dp"
android:id="#+id/data"
android:text="list"/>
</ScrollView>
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/userList"
/>
</RelativeLayout>
The ActivityMain.Java :
package com.example.webdownload;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.webdownload.databinding.ActivityMainBinding;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
ArrayList<String> userList;
ArrayAdapter<String> listAdapter;
Handler mainHandler= new Handler();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initializeUserList();
binding.data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new fetchData().start();
}
});
}
private void initializeUserList() {
userList = new ArrayList<>();
listAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,userList);
binding.userList.setAdapter(listAdapter);
}
class fetchData extends Thread{
String data = "";
#Override
public void run() {
mainHandler.post(new Runnable() {
#Override
public void run() {
progressDialog =new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching Data");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
try {
URL url =new URL("http://myjson.dit.upm.es/api/bins/1anx");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line;
while ((line= bufferedReader.readLine())!= null){
data = data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
JSONArray users = jsonObject.getJSONArray("Users");
userList.clear();
for(int i =0;i<users.length();i++){
JSONObject names = users.getJSONObject(i);
String name = names.getString("name");
userList.add(name);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
mainHandler.post(new Runnable() {
#Override
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
listAdapter.notifyDataSetChanged();
}
});
}
}
}
I Think This is happening because your JSON URL have some spelling mistake
The spelling of name (namr) is wrong
You can check your json url - Your wrong json url

Go to full image screen

I have made an android app to display image from firebase into recycler view and when user click a image it has to go to its full screen page and have tried a several times but it just shows the blank activity
You can use PhotoView library (com.github.chrisbanes.photoview) to show full screen picture as below:
Piccaso is used here to show images, but you can use other image libraries such as Fresco, Glide .
ActivityLargeImageView
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.github.chrisbanes.photoview.PhotoView;
import com.github.chrisbanes.photoview.PhotoViewAttacher;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ActivityLargeImageView extends FragmentActivity {
#BindView(R.id.photoview_image)
PhotoView photoviewImage;
#BindView(R.id.progressbar)
ProgressBar progressBar;
File mFile;
PhotoViewAttacher mAttacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_large_image_view);
ButterKnife.bind(this);
progressBar.setVisibility(View.VISIBLE);
String img_url = getIntent().getExtras().getString("image_url");
try {
mFile = new File(img_url);
} catch (Exception ex) {
}
if (mFile.exists()) {
Picasso.with(getApplicationContext()).load(mFile).into(photoviewImage, imageLoadedCallback);
} else {
Picasso.with(getApplicationContext()).load(img_url).into(photoviewImage, imageLoadedCallback);
}
}
Callback imageLoadedCallback = new Callback() {
#Override
public void onSuccess() {
if (mAttacher != null) {
mAttacher.update();
} else {
mAttacher = new PhotoViewAttacher(photoviewImage);
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.error_message_connection_to_server), Toast.LENGTH_LONG).show();
}
};
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:background="#000000"
android:orientation="vertical" >
<com.github.chrisbanes.photoview.PhotoView
android:id="#+id/photoview_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>

Why getting message unfortunately has stopped when adding button click event?

Without the button code it's working fine.
I didn't see anything in the LogCat.
This is the MainActivity.java code:
package com.test.webservertest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.support.v7.app.ActionBarActivity;
import android.util.AndroidRuntimeException;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.Context;
import android.view.View.OnClickListener;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Locale;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.*;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Logger;
import android.widget.Button;
public class MainActivity extends ActionBarActivity
{
private static final int MY_DATA_CHECK_CODE = 0;
public static MainActivity currentActivity;
TextToSpeech mTts;
private String targetURL;
private String urlParameters;
private Button btnClick;
private String clicking = "clicked";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(new SingleTouchEventView(this, null));
addListenerOnButton();
currentActivity = this;
initTTS();
}
public void addListenerOnButton() {
btnClick = (Button) findViewById(R.id.checkipbutton);
btnClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.mkyong.com"));
startActivity(browserIntent);
}
});
}
And in the layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:text="WEBSERVER"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="50dp"
android:textColor="#FFF"
android:id="#+id/textView"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Ip"
android:id="#+id/checkipbutton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
If i'm calling the method: addListenerOnButton(); i'm getting message on the android: unfortunately has stopped and then the program shut down.
If i'm not calling addListenerOnButton(); then the program will keep working fine.
Also when running the program if not calling the addListenerOnButton(); i don't see the button i added in the layout designer on the screen at all.
you set the contentview twice cancelling the first with the layout of the button in it
if you comment out the second call to setContentView it may work
setContentView(R.layout.activity_main);
//setContentView(new SingleTouchEventView(this, null));
if you wish to use
SingleTouchEventView
consider adding it to your activity_main layout

Parse Html from website with android studio, Java

I am making this question today because I can not find certain information on google and/or Stack Overflow. My Problem is, I am creating a Android Application and I want certain information from a Website. So I use Jsoup as my parse Library. I follow all the instruction and set The data in the Text to Show up with The HTML text. For Some reason it is either a network connection or my code is wrong in communicating with the website? I do not know what is up with the app. I am Using Android Studio, so when running either the emulator or on a device it will just not pull html from the website.
Here is My code for 2 Classes. This has to be in Java.
package update.app.jdog1218.com.messingaround;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends Activity {
private Button answer_Button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RelativeLayout bible = new RelativeLayout(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
public void gotoInbeddedBible(MenuItem item) {
Intent bibleclass = new Intent(this, bible.class);
final int result = 1;
bibleclass.putExtra("callingActivity", "MainActivity");
startActivity(bibleclass);
startActivityForResult(bibleclass, result);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
public void exit(MenuItem item) {
Button exitProcess = (Button) findViewById(R.id.submit);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
public void sotd(MenuItem item) {
Intent clickedSotd = new Intent(this, Sotd.class);
int result = 1;
startActivity(clickedSotd);
}
}
This is the class I want to use Jsoup in.
package update.app.jdog1218.com.messingaround;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.Menu;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.Connection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
import java.io.IOException;
import static org.jsoup.Jsoup.*;
/*
* Created by Joel on 5/28/2015.
*/
public class Sotd extends Activity {
#Override
protected void onStart() {
super.onStart();
}
String title;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.sotd);
Intent activityThatCalled = getIntent();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
/**
* Pull and Parse the HTML of Compass HB for SOTD.
*
* #return DocumentString
* #throws IOException
*/
protected String pullHTML() {
super.onStart();
final String url = "https://www.compasshb.com/api/v1/passages";
Document doc = null;
TextView textView = (TextView) findViewById(R.id.SOTD);
try {
doc = Jsoup.connect(url).get();
textView.setText(doc.ownText());
String paragraph = doc.title();
return paragraph;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostResume() {
super.onPostResume();
}
}
This is the XML File for the Layout I want to output too.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:weightSum="1"
android:background="#drawable/the_rendered_background">
<TextView
android:text="#string/text_of_activity_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:height="40dp"
android:capitalize="none"
android:width="200dp"
android:textColor="#000000"
android:id="#+id/text_view" />
</LinearLayout>
SOTD is where I want it to output too.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".Sotd"
android:weightSum="1"
android:background="#drawable/the_rendered_background"
android:backgroundTintMode="add">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/SOTD"
/>
</LinearLayout>
Pretty Much I just need someone to tell me what I am doing wrong./Review

android - list cannot be resolved or is not a field

I ve been searching for hours and I can't figure out what I'm doing wrong.
"list cannot be resolved or is not a field"
here is my search.java file:
package com.example.testxxx;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Search extends ListActivity {
private TextView mTextView;
private ListView mListView;
private String query;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
mTextView = (TextView) findViewById(R.id.text);
mListView = (ListView) findViewById(R.id.list);
}
}
and here is my search.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Search" >
<TextView
android:id="#+id/text"
android:textColor="?android:textColorPrimary"
android:background="#android:drawable/title_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dp" />
</RelativeLayout>
I have noticed that if i change
android:id="#android:id/list"
to
android:id="#android:id/list"
then it will find it, but if i do so, i will have another error because I am extending listactivity that need the listview to have the ID set this way (android:id="#android:id/list")
Do you have a solution? Thank you!
Just replace
mListView = (ListView) findViewById(R.id.list);
with
mListView = (ListView) findViewById(android.R.id.list);
or simply you can call
mListView = getListView()
as you are extending ListActivity and your xml layout contains a ListView with id android.R.id.list
when you referencing to internal ID's (ID's may be drawable ID's, String ID's or any resource) then those ID's will not be generated in your R.java. you have to import those ID's from where you referenced.

Categories

Resources