how to extract html code from webview - android

this is my code ...... i cant resolve the error..
import java.io.IOException;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
#SuppressLint("SetJavaScriptEnabled")
public class Social_media extends Fragment {
private String getDownloadButtonOnly(String url){
URI http ;
HttpGet pageGet = new HttpGet ( "http://visiblenews.com/category/gadgets/");
ResponseHandler<String> handler = new ResponseHandler<String>() {
public String handleResponse1(HttpResponse response) throws ClientProtocolException, IOException {
HttpEntity entity = response.getEntity();
String html;
if (entity != null) {
html = EntityUtils.toString(entity);
return html;
}else {
return null;
}
}
#Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
return null;
}
};
Object pageHTML = null;
try {
while (pageHTML==null){
Object client;
pageHTML = ((Object) client).execute(pageGet, handler);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Pattern pattern = Pattern.compile("<h2>Direct Down.+?</h2>(</div>)*(.+?)<.+?>", Pattern.DOTALL);
Matcher matcher = pattern.matcher((CharSequence) pageHTML);
String displayHTML = null;
while(matcher.find()){
displayHTML = matcher.group();
}
return displayHTML;
}
public void customizeWebView(final ServiceCommunicableActivity activity, final WebView webview, final SearchResult mRom) {
mRom.setFileSize(getFileSize(mRom.getURLSuffix()));
webview.getSettings().setJavaScriptEnabled(true);
}
private Object getFileSize(Object urlSuffix) {
// TODO Auto-generated method stub
return null;
}};
error log is ..
Description Resource Path Location Type
The method execute(HttpGet, ResponseHandler) is undefined for the type Object Social_media.java /TabsWithSwipeGesture/src/info/androidhive/tabsswipe line 62 Java Problem

Object has no execute() method. You are supposed to use a HttpClient instance. Further I wonder what you want with pageHtml (and the loop there) as the html page will be availabel in `handleResponse'. Further the title of your post is strange as there is no WebView involved here.

Related

cannot resolve symbol okhttp

i am developing a gcm chat app in android studio and i am getting this error n no idea how to resolve it. i searched about it but didn't find any thing.
Here is the code and in MainActivity.java also having same problem.
package com.example.jason.androidchat2;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
new SendMessage().execute();
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();;
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
OkHTTP is an Open Source project designed to be an efficient HTTP client.
Just add this in your build.gradle
dependencies {
compile 'com.squareup.okhttp:okhttp:2.5.0'
}
FYI
The latest release is available
implementation 'com.squareup.okhttp3:okhttp:4.9.0'

WebViewClient to load existing session from HTTPClient Call for Android

Issue: I have two URLs that I need to call simultaneous to validate my session and directly enter to my Home (or other) pages. I am trying to call my first URL through HTTPClient execute and validate the session (Can call Login). Now second call is directly through WebView so that I can reach to my HomePage, instead of Login Page.
Below is my code. I refered lot of links and blogs but non of worked for me. I am putting my code here. Please provide your inputs if any.
package com.example.samplewebview;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Menu;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieSyncManager.createInstance(MainActivity.this);
myWebView = (WebView)findViewById(R.id.webView1);
new WebViewTask().execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class WebViewTask extends AsyncTask<Void, Void, Boolean> {
String sessionCookie;
CookieManager cookieManager;
String url1 = "http://domain.com/validateURL=sessionid";
String url2 = "http://domain.com/WebViewURLToLoad";
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Boolean doInBackground(Void... param) {
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpGet httpGet = new HttpGet(url1);
HttpUriRequest request = new HttpGet(url1);
try {
HttpResponse response = httpClient.execute(request);
List<Cookie> cookies = httpClient.getCookieStore().getCookies();
for (int i = 0; i < cookies.size(); i++) {
Cookie cookie = cookies.get(i);
System.out.println("Name : "+cookie.getName()+" --- Value"+cookie.getValue());
}
cookieManager = CookieManager.getInstance();
//cookieManager.acceptCookie();
sessionCookie = cookieManager.getCookie(url1);
//sessionCookie = new PersistentConfig(getApplicationContext()).getCookieString();
//sessionCookie = new String("test");
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
}
CookieSyncManager.createInstance(getApplicationContext()).sync();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SystemClock.sleep(1000);
return false;
}
#Override
protected void onPostExecute(Boolean result) {
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
if (sessionCookie != null) {
cookieManager.setCookie(url2, sessionCookie);
CookieSyncManager.getInstance().sync();
Toast.makeText(getApplicationContext(), url2, Toast.LENGTH_LONG).show();
}
//super.onPageStarted(view, url, favicon);
}
});
myWebView.loadUrl(url2);
}
}
}

HttpResponse.execute() throws exception

I'm trying to develop a simple app that gets data from web service and displays it
It throws exception exactly when he calls response.execute(client)
package com.example.webbasedapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
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 android.util.Log;
public class GETMethods {
public String getInternetData() throws Exception{
BufferedReader in=null;
String Data=null;
try{
HttpClient client=new DefaultHttpClient();
URI web=new URI("http://www.mybringback.com/");
HttpGet request = new HttpGet();
request.setURI(web);
HttpResponse reponse=client.execute(request);
Log.v("response code", reponse.getStatusLine()
.getStatusCode() + "");
InputStream inp=reponse.getEntity().getContent();
in=new BufferedReader(new InputStreamReader(inp));
StringBuffer buf=new StringBuffer();
String l="";
String nl=System.getProperty("line.separator");
while((l=in.readLine())!=null){
buf.append(l+nl);
}
in.close();
Data=buf.toString();
return Data;
}finally{
if(in!=null){
try{
in.close();
return Data;
}catch (Exception e){
Log.d("error",e.toString());
}
}
}
}
}
And this is my main activity
package com.example.webbasedapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
TextView test = (TextView) findViewById(R.id.data);
GETMethods data = new GETMethods();
String d = null;
try {
d = data.getInternetData();
// test.setText(d);
} catch (Exception e) {
// TODO Auto-generated catch block
d = "bla";
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
// Log.d("testW",e.getMessage());
}
test.setText(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
You are attempting to access the network on the UI thread which is not allowed due to potential hangup issues. Look into AysncTask and implement GETMethods as one of them. It will look something like this:
public class GETMethods extends AsyncTask<String, Void, String>{
protected void doInBackground(String... params){
YourNetworkCode
}
}

wrong in json parsing

please help me to find the error in this code.
I want to get some data from remote server (php & mysql) by json then parsing it
the problem is that result returns null but it is supposed to return name at this link :
http://codeincloud.tk/json_android_example.php
package com.shadatv.shada;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class canticlesActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeincloud.tk/json_android_example.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
httpStuff = (TextView) findViewById(R.id.textView1);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ahmed .. " + result, Toast.LENGTH_LONG).show();
httpStuff.setText(result);
}
}
}
parse current json String as :
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
// convert data to json object
JSONObject last =new JSONObject(data);
because current webservice retuning an JSONObject only instead of JSONArray
Your URL provides the following data:
{"name":"Froyo","version":"Android 2.2"}
The chunk of code parsing the JSON is the following:
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
That makes the assumption that the JSON document you're reading is an Array instead of an Object. (Either is valid JSON, but the document you're fetching is quite clearly an Object). Web service calls may not always be returning one or the other so you'll have to take care that you're parsing against the correct type.
copy and past now it is working.
i changed JSONObject last =new JSONObject(data);
because http://codeincloud.tk/json_android_example.php retuning an JSONObject
package com.shadatv.shada;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class canticlesActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://codeincloud.tk/json_android_example.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
httpStuff = (TextView) findViewById(R.id.textView1);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONObject last = new JSONObject(data);
return last;
} else {
Toast.makeText(getBaseContext(), "error", Toast.LENGTH_SHORT);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ahmed .. " + result, Toast.LENGTH_LONG).show();
httpStuff.setText(result);
}
}
}
Better to use GSON Library which is much simpler then doing manual parsing.
Link for the library is : http://code.google.com/p/google-gson/

Not getting the output

I'm trying to get the data from the database for which I created a php file. It returns the name as the reply to the call. the website it Ensignweb
the program code goes like this.
The php file is like this
<?php
$connect = mysql_connect("localhost","databasename","password");
mysql_select_db("ews_app");
$query = mysql_query("select name from comment");
if(!empty($query)){
if(mysql_num_rows($query)>0){
WHILE($row=mysql_fetch_array($query)):
$comment = array();
$comment["name"] = $row['name'];
echo "$comment<br>";
echo json_encode($comment);
echo "<br>";
endwhile;
}
}
?>
The java code goes like this:
import java.io.IOException;
import java.io.Reader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView httpStuff;
HttpClient client;
JSONObject json;
final static String URL = "http://www.ensignweb.com/sandbox/app/comment11.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
httpStuff = (TextView) findViewById(R.id.data);
client = new DefaultHttpClient();
new Read().execute("name");
}
public JSONObject lastTweet() throws ClientProtocolException,IOException,JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();//return 200 if execution is success
if(status==200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_LONG);
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet();
return json.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
httpStuff.setText(result);
}
}
}
But It is not displaying the json reply. I'm stucked in it from past few days.
Please help me out of it. I really need it.

Categories

Resources