[Q] App doesn't get site source code - Android Q&A, Help & Troubleshooting

Hey xda-members,
Before I tell my problem I want to say that I tried real hard to follow the rules and find the right place to post my question in. I hope I found the right place to ask, if not I'm really sorry about that. :angel:
I'm new to Android development and read through some basics and tryed some things, now I wanted to expand my knowledge and try to regex some information from a website's source code. That thing was never a problem before when I used just java, but here in Android Studio it makes a difference somewhere, I followed the book I've read and put the "<uses-permission android:name="android.permission.INTERNET" />" in the AndroidManifest.xml and tryed all kind of ways to get the source code of an specified URL, but couldn't do it, sometimes it didn't do anything and just jumped to the error catch and sometimes it just returned an empty string.
My current code looks like this:
Code:
package com.example.onlineregex;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.EditText;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View view) {
get_source();
}
});
}
void get_source()
{
TextView src = (TextView) findViewById(R.id.textView1);
try {
URL daurl = new URL(""); // Some URL, removed because of 10 posts thing
URLConnection conn = daurl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
String finalout = "";
while ((inputLine = in.readLine()) != null)
finalout += inputLine;
in.close();
src.setText(finalout);
}
catch (Exception e) {
src.setText(e.getMessage());
}
}
}
nothing special I could do wrong I guess.
I hope you could help me out with this, because I can't solve this on my own, even after reading through all kinds of suggestions..
Greetz

Related

Android App Help

Ok so today i started my first Android Application in eclipse. I am VERY new at coding so bear with me. So i looked online on how to open a new screen when i press a button, but my question is, how do i open a different screen when i press a different button on the same page? Because you cant just copy and paste the same code for the first button because it gives you duplicate errors. Can anyone tell me what i can copy/paste or do to get my second button to go to a different screen? Thanks!
main.class (or java)
Code:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MinecraftInfoProActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton(){
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(context, Mobs.class);
startActivity(intent);
}
});
}
}
main.xml
Code:
animals.class (or java) (this is my second page i wanna hook my second button up to)
Code:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Animals extends Activity {
}
animals.xml
Code:
AndroidManifest.xml
Code:
I am trying to hook button2 in main.xml so that when clicked, it takes me to the animals.xml page. Any help is appreciated guys. Thanks
EDIT: Sorry about the smily faces in the code..im not sure what that is about.
Mod Edit: Moved to Q&A
Scoutamis said:
Ok so today i started my first Android Application in eclipse. I am VERY new at coding so bear with me. So i looked online on how to open a new screen when i press a button, but my question is, how do i open a different screen when i press a different button on the same page? Because you cant just copy and paste the same code for the first button because it gives you duplicate errors. Can anyone tell me what i can copy/paste or do to get my second button to go to a different screen? Thanks!
main.class (or java)
Code:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
public class MinecraftInfoProActivity extends Activity {
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton(){
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(context, Mobs.class);
startActivity(intent);
}
});
}
}
main.xml
Code:
animals.class (or java) (this is my second page i wanna hook my second button up to)
Code:
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Animals extends Activity {
}
animals.xml
Code:
AndroidManifest.xml
Code:
I am trying to hook button2 in main.xml so that when clicked, it takes me to the animals.xml page. Any help is appreciated guys. Thanks
EDIT: Sorry about the smily faces in the code..im not sure what that is about.
Click to expand...
Click to collapse
Use CODE] /CODE] If you dont want smileys.
Sent from my GT-I5800 using XDA App
rubensollie said:
Use CODE] /CODE] If you dont want smileys.
Sent from my GT-I5800 using XDA App
Click to expand...
Click to collapse
I did so idk why it isn't working...anyway does ANYONE have any help?
Sent from my SAMSUNG-SGH-I727 using xda premium
Hope this helps ya out
In the main.xml, you can specify an event handler method for button2 by adding this in button2's xml declarations
Code:
android:onClick="yourMethodName"
That is a quick replacement for
Code:
button.setOnClickListener(new OnClickListener(){
public void yourMethodName(View view) {
Intent intent = new Intent(context, Mobs.class);
startActivity(intent);
}
});
Of course replace 'yourMethodName' with the method that you want to handle the click action. You can use this for button1 as well, just specify the onClick property in main.xml under button1. You need to create a method in your MinecraftInfoProActivity class that will be the handler for the button, so say you create a method called 'Button2Handler". To open up Animals (which you have to write the code to display the animals.xml) you could use this method.
Code:
public void Button2Handler(View view) {
Intent intent = new Intent(context, Animals.class);
startActivity(intent);
}
Hope this gives you what you need, as it's just a quick basic intro into it
regaw_leinad said:
Hope this helps ya out
In the main.xml, you can specify an event handler method for button2 by adding this in button2's xml declarations
Code:
android:onClick="yourMethodName"
That is a quick replacement for
Code:
button.setOnClickListener(new OnClickListener(){
public void yourMethodName(View view) {
Intent intent = new Intent(context, Mobs.class);
startActivity(intent);
}
});
Of course replace 'yourMethodName' with the method that you want to handle the click action. You can use this for button1 as well, just specify the onClick property in main.xml under button1. You need to create a method in your MinecraftInfoProActivity class that will be the handler for the button, so say you create a method called 'Button2Handler". To open up Animals (which you have to write the code to display the animals.xml) you could use this method.
Code:
public void Button2Handler(View view) {
Intent intent = new Intent(context, Animals.class);
startActivity(intent);
}
Hope this gives you what you need, as it's just a quick basic intro into it
Click to expand...
Click to collapse
Omg thank you that helped soooo much
Sent from my SAMSUNG-SGH-I727 using xda premium

[Q] Need help developing Web Browser usng WebView

Hello guys, im sorry if this is not the right section, please move if necessary.
Im developing my own Chrome like Web Browser in Eclipse using WebView, so far its just a TextEdit that act as a url bar, a GO button to take WebView to whatever URL is typed, and of course the WebView showing this website, now i have some issues, and i been up and down everywhere and cant find the answers for these issues, maybe someone here can shed some light.
1- when i go lets say msn.com, it goes fine but if i click -- news -- , it goes fine too, but the "URL bar" still show msn.com , it doesn't show the current URL im in, so its there a way to write to to the TextEdit or create a real url bar?
2- when i go to YouTube, if i hit play on a video it plays fine on WebView, but if i turn the device sideways, video shows liek to hit play again but you can still hear it in the background, if i hit play it just stop and wont play again any other videos, ( i found the YouTube API player and i followed what supposedly is how to use it but it never worked, i cant really find instructions on how to merge it to the app, supposedly just moved the .jar file but still playing in the browser) or how can i do in webview so when a user press play it ask you want to use browser or you want to launch youtube app, cant manage how to set up in intent for this activity.
Or how can i lunch youtube app from a button on my layout?
3- How to make android , in this case 4.0.4 recognize my app as a browser so whenever any app ask me to launch a browser, mine is on the list.
4- on my case ( galaxy s2 ) in chrome when i press menu, it pop this menu, on my app, menu key pop a little menu with settings only, but nothing happens ( of course ), how can i add items to this main menu, like About, Contact Me, Back , Forward and add stuff in settings too?
5- launch an app from a button on the app.
I know its a lot but any help would be greatly appreciated it
I'm not an expert, but i'll try to answer your questions...
cubanito08 said:
1- when i go lets say msn.com, it goes fine but if i click -- news -- , it goes fine too, but the "URL bar" still show msn.com , it doesn't show the current URL im in, so its there a way to write to to the TextEdit or create a real url bar?
Click to expand...
Click to collapse
Get the url for the current page using getURL() and set it as content to your URL Bar (using its setText method).
cubanito08 said:
2- ... or how can i do in webview so when a user press play it ask you want to use browser or you want to launch youtube app, cant manage how to set up in intent for this activity.
Click to expand...
Click to collapse
Check here.
cubanito08 said:
3- How to make android , in this case 4.0.4 recognize my app as a browser so whenever any app ask me to launch a browser, mine is on the list.
Click to expand...
Click to collapse
Add this to your AndroidManifest:
Code:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http"/>
</intent-filter>
Source.
cubanito08 said:
4- ... how can i add items to this main menu, like About, Contact Me, Back , Forward and add stuff in settings too?
Click to expand...
Click to collapse
Check this, a well-explained tutorial.
cubanito08 said:
5- launch an app from a button on the app.
Click to expand...
Click to collapse
Add a listener to your button, and launch and intent. For example, to launch YouTube:
Code:
final Button YouTube = (Button) findViewById(R.id.yourButtonID);
YouTube.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
PackageManager manager = getPackageManager();
i = manager.getLaunchIntentForPackage("com.google.android.youtube"); //com.google.android.youtube is the Package Name for youtube
i.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(i);
}
});
Source.
How can you get the package name for other apps? It depends of the app. If it is hosted in Play Store, it's too easy: go to Play Store and search the app. Check the url, will be something like this:
Code:
https://play.google.com/store/apps/details?id=com.google.android.youtube&feature=nav_result...
The text between id= and &feature is the package name. So easy as that.
Otherwise, if you wish to open a system app (settings, stock browser, or something like that) I recommend you to use DDMS (it's a debug app included in Android SDK. It's located at AndroidSDKPath\tools). Simply open it with your phone connected, and open any app from your phone. DDMS will show you some debug info, included the package name of the open apps.
thanks rober is been really helpful, but one question where do i set the geturl() on my main.java? also for the youtube i tried those and i cant manage, can you take a look at my main.java please?
package com.foka.icecold;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.FactoryConfigurationError;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.LinearLayout.LayoutParams;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
@SuppressWarnings("unused")
public class Main extends Activity implements View.OnClickListener{
private static final String TAG = "my webview 2";
private WebView mWebView;
EditText url; ------------------------------------------------------------ this is my " url bar"
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "onCreate");
String extra = getIntent().getStringExtra("VideosId");
mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new IceColdClient());
mWebView.getTouchables();
url = (EditText) findViewById(R.id.web);
Button go = (Button) findViewById(R.id.go);
Button Back = (Button) findViewById(R.id.back);
Button foward = (Button) findViewById(R.id.foward);
Button refresh = (Button) findViewById(R.id.refresh);
Button test = (Button) findViewById(R.id.testbutton);
Button fb = (Button) findViewById(R.id.fb);
Button tw = (Button) findViewById(R.id.tw);
Button yt = (Button) findViewById(R.id.yt);
Button map = (Button) findViewById(R.id.maps);
Button weat = (Button) findViewById(R.id.weather);
Button news = (Button) findViewById(R.id.news);
go.setOnClickListener(this);
Back.setOnClickListener(this);
foward.setOnClickListener(this);
refresh.setOnClickListener(this);
test.setOnClickListener(this);
fb.setOnClickListener(this);
tw.setOnClickListener(this);
yt.setOnClickListener(this);
map.setOnClickListener(this);
weat.setOnClickListener(this);
news.setOnClickListener(this);
--------------------------------------------------------------------------- i tried inserting here the intent here for youtube app but it launches the youtube app when i launch my app
final Activity activity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient());
}
public void onClick(View v) {
switch (v.getId()){
case R.id.go:
String theWebsite = url.getText().toString();
if(!theWebsite.startsWith("www.")&& !theWebsite.startsWith("http://")){
theWebsite = "www."+theWebsite;
}
if(!theWebsite.startsWith("http://")){
theWebsite = "http://"+theWebsite;
mWebView.loadUrl(theWebsite);
}
break;
case R.id.back:
if (mWebView.canGoBack())
mWebView.goBack();
break;
case R.id.foward:
if (mWebView.canGoForward())
mWebView.goForward();
break;
case R.id.refresh:
mWebView.reload();
break;
case R.id.testbutton:
mWebView.loadUrl("http://www.google.com");
break;
case R.id.fb:
mWebView.loadUrl("http://www.facebook.com");
break;
case R.id.tw:
mWebView.loadUrl("http://www.twitter.com");
break;
case R.id.yt:
mWebView.loadUrl("http://www.youtube.com");
break;
case R.id.maps:
mWebView.loadUrl("http://maps.google.com/");
break;
case R.id.weather:
mWebView.loadUrl("http://www.weather.com/");
break;
case R.id.news:
mWebView.loadUrl("http://www.msn.com/");
break;
}
}
private class IceColdClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
@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;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onStart()
{
super.onStart();
Log.i(TAG, "onStart");
}
@Override
protected void onRestart()
{
super.onStart();
Log.i(TAG, "onRestart");
}
@Override
protected void onPause()
{
super.onPause();
Log.i(TAG, "onPause");
}
@Override
protected void onResume()
{
super.onResume();
Log.i(TAG, "onResume");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
protected void onStop()
{
super.onStop();
Log.i(TAG, "onStop");
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
Log.i(TAG, "onSaveInstanceState");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
Log.i(TAG, "onRestoreInstanceState");
}
public static boolean isAppInstalled(String uri, Context context) {
PackageManager pm = context.getPackageManager();
boolean installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
return installed;
}
}
Click to expand...
Click to collapse
Ok, here you should put the code to open Youtube:
Code:
case R.id.yt:
//mWebView.loadUrl("http://www.youtube.com");
//Put here the intent
break;
And... I'm not sure, but I think you can use getURL() and set the result to your URL Bar here:
Code:
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
//getURL()... and that stuff here.
}
thanks , i remove all case R.id.xx sicne they were buttons on the layout that looked horrible i just rather wait for user to go to the site and launch the intent when press play, thats where my issues is, and for the geturl() i cant get it how do i write it to the EditText overriding whatever is there already typed by user?
this is my new java and thanks to u i manage to create the menu
package com.foka.icecold;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.FactoryConfigurationError;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.LinearLayout.LayoutParams;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
@SuppressWarnings("unused")
public class Main extends Activity implements View.OnClickListener{
private static final String TAG = "my webview 2";
private WebView mWebView;
EditText url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "onCreate");
String extra = getIntent().getStringExtra("VideosId");
mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new IceColdClient());
mWebView.getTouchables();
url = (EditText) findViewById(R.id.web);
Button go = (Button) findViewById(R.id.go);
Button home = (Button) findViewById(R.id.home);
go.setOnClickListener(this);
home.setOnClickListener(this);
final Activity activity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});
mWebView.setWebViewClient(new WebViewClient()()
mWebView.setWebViewClient(new WebViewClient());
}
public void onClick(View v) {
switch (v.getId()){
case R.id.go:
String theWebsite = url.getText().toString();
if(!theWebsite.startsWith("www.")&& !theWebsite.startsWith("http://")){
theWebsite = "www."+theWebsite;
}
if(!theWebsite.startsWith("http://")){
theWebsite = "http://"+theWebsite;
mWebView.loadUrl(theWebsite);
}
break;
case R.id.home:
mWebView.loadUrl("http://www.google.com");
break;
}
}
private class IceColdClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about_menuitem:
startActivity(new Intent(this, About.class));
return true;
case R.id.help_menuitem:
startActivity(new Intent(this, Help.class));
return true;
case R.id.foward_menuitem:
if (mWebView.canGoForward())
mWebView.goForward();
return true;
case R.id.refresh_menuitem:
mWebView.reload();
return true;
case R.id.home_menuitem:
mWebView.loadUrl("http://www.google.com");
return true;
case R.id.back_menuitem:
mWebView.goBack();
return true;
case R.id.clear_menuitem:
mWebView.clearHistory();
return true;
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onStart()
{
super.onStart();
Log.i(TAG, "onStart");
}
@Override
protected void onRestart()
{
super.onStart();
Log.i(TAG, "onRestart");
}
@Override
protected void onPause()
{
super.onPause();
Log.i(TAG, "onPause");
}
@Override
protected void onResume()
{
super.onResume();
Log.i(TAG, "onResume");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
protected void onStop()
{
super.onStop();
Log.i(TAG, "onStop");
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
Log.i(TAG, "onSaveInstanceState");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
Log.i(TAG, "onRestoreInstanceState");
}
public static boolean isAppInstalled(String uri, Context context) {
PackageManager pm = context.getPackageManager();
boolean installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
return installed;
}
}
Click to expand...
Click to collapse
Something like this:
Code:
...
activity.setProgress(progress * 1000);
url.setText(mWebView.getURL()) //You can use getOriginalURL() instead getURL()
}
...
//If that works, but you can't edit the URL anymore, use this:
...
activity.setProgress(progress * 1000);
url.setText(mWebView.getURL(),TextView.BufferType.EDITABLE)
}
...
ill try it when i get home, this is driving me crazy, also the youtube thing, video even play fine in webview but when u turn it landscape then it goes crazy, so i want to give the user the chance to choose either youtube app or browser but that they can turn and video either stop and let them play again or that keep playing, but i cant find where to insert the intent for it and how does it knows the user pressed play on the video
Yeah, looks difficult (at least to me).
I have an idea (pretty elegant... haha ). You can analyze the URL to know if there is a video on the screen. If so, add a new option in the Menu (something like Play on Youtube App), so the user can play the video directly on your browser, or using the Youtube app.
omg thanks so much url works fine now !!!!!!!!!!!!. but lets say if i input www.yahoo.com , while the browser go there it replaces the text with the current url www.google.com while it load the next one, anyway to stop this from happening so when i write yahoo.com it stays there and only override when page change, cause sometimes i try to write a url and since current page still something loading it writes me back the url of the current page, its so annoying, i just want to write the url when the page start loading , not when its loading to a new one too
i have this
WebView web=new WebView(this);
web.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// can get Here
view.getUrl();
//Now set to TExtView
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
// can get Here
view.getUrl();
//Now set to TExtView
}
});
Click to expand...
Click to collapse
but i cant fidn right way to incorporate it into my java and only when page start not when page finished
if i do this
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
// can get Here
mwebview.getUrl();
url.setText(mWebView.getUrl());
[/COLOR]
i get setText error The method setText(String) is undefined for the type String
}
Click to expand...
Click to collapse
last 2 question and ill leave u alone for tonite lol, if im goign to insert a new piece of code , lets say the youtube intent or something else for a browser how do i know im inserting it in the right part fo the java file or should i keep going at the end, and is it possible to turn stuff on and off liek add to a menu the option to turn setJavaScriptEnabled(true) or false so the user can decide if they want it or not ?
Your code is giving error because onPageStarted has an argument named as your URL Bar (url), simply rename that argument and the error will be gone. Even better, you can use that argument to get the URL, without getUrl(), like this:
Code:
public void onPageStarted(WebView view, String URL, Bitmap favicon) {
super.onPageStarted(view, URL, favicon);
url.setText(URL); //Note the change in the argument's name (url to URL)
}
cubanito08 said:
...if im goign to insert a new piece of code , lets say the youtube intent or something else for a browser how do i know im inserting it in the right part fo the java file or should i keep going at the end...
Click to expand...
Click to collapse
While your code doesn't give you errors... don't matter the location haha
cubanito08 said:
and is it possible to turn stuff on and off liek add to a menu the option to turn setJavaScriptEnabled(true) or false so the user can decide if they want it or not ?
Click to expand...
Click to collapse
Sure. I think you mean an options menu as many other apps, right? Those menus are done using the SharedPreferences (relatively easy, the API makes almost all the job, you only need to recover the preferences values, and apply them to your app).
but im using WebChromeClient so i can run javascripts like youtube player so PageStarted doesnt show under it... so for some reason i dont know if PageStarted can be incorporated on it or if it has to be a regula WebViewClient only ?
this video show one of the issues
http://www.youtube.com/watch?v=K5DtJJ5zOe0
as you can see main page is google.com, then when i type yahoo.com , it writes google.com again then it goes to yahoo.com, then when i load msn sincew my signal is crap it takes a while to load and it wont let me type another website since it keep writing the url nonstop until site finish loading.
this is my new main.java, as you see i nthe red part i have a chromeclient and geturl and it get the url as u see in the video but i cant find how to set it to just pagestart since chromeclient doesnt let me add it
package com.foka.icecold;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.FactoryConfigurationError;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;
import android.widget.LinearLayout.LayoutParams;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@SuppressWarnings("unused")
public class Main extends Activity implements View.OnClickListener{
private static final String TAG = "my webview 2";
private WebView mWebView;
EditText url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "onCreate");
String extra = getIntent().getStringExtra("VideosId");
mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("http://www.google.com");
mWebView.setWebViewClient(new IceColdClient());
mWebView.getTouchables();
url = (EditText) findViewById(R.id.web);
Button go = (Button) findViewById(R.id.go);
go.setOnClickListener(this);
final Activity activity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
url.setText(mWebView.getUrl());
}
});
}
public void onClick(View v) {
switch (v.getId()){
case R.id.go:
String theWebsite = url.getText().toString();
if(!theWebsite.startsWith("www.")&& !theWebsite.startsWith("http://")){
theWebsite = "www."+theWebsite;
}
if(!theWebsite.startsWith("http://")){
theWebsite = "http://"+theWebsite;
mWebView.loadUrl(theWebsite);
}
break;
}
}
private class IceColdClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView webview, String url)
{
webview.loadUrl(url);
return true;
}
}
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;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.about_menuitem:
startActivity(new Intent(this, About.class));
return true;
case R.id.help_menuitem:
startActivity(new Intent(this, Help.class));
return true;
case R.id.foward_menuitem:
if (mWebView.canGoForward())
mWebView.goForward();
return true;
case R.id.refresh_menuitem:
mWebView.reload();
return true;
case R.id.home_menuitem:
mWebView.loadUrl("http://www.google.com");
return true;
case R.id.back_menuitem:
mWebView.goBack();
return true;
case R.id.clear_menuitem:
mWebView.clearHistory();
return true;
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onStart()
{
super.onStart();
Log.i(TAG, "onStart");
}
@Override
protected void onRestart()
{
super.onStart();
Log.i(TAG, "onRestart");
}
@Override
protected void onPause()
{
super.onPause();
Log.i(TAG, "onPause");
}
@Override
protected void onResume()
{
super.onResume();
Log.i(TAG, "onResume");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.i(TAG, "onDestroy");
}
@Override
protected void onStop()
{
super.onStop();
Log.i(TAG, "onStop");
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
Log.i(TAG, "onSaveInstanceState");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
Log.i(TAG, "onRestoreInstanceState");
}
public static boolean isAppInstalled(String uri, Context context) {
PackageManager pm = context.getPackageManager();
boolean installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
installed = true;
} catch (PackageManager.NameNotFoundException e) {
installed = false;
}
return installed;
}
}
Click to expand...
Click to collapse

Help! Simple app not working... why? (Android Studio)

Dear friends,
i just started to develop android apps for my smartphone. like a few days ago. I have c and c++ experiences in programming, but I am kinda new to java/android. So I would appreciate some support a lot.
One of my first apps is not working and I can't understand why. Here is the main code (BTW, I know that i definately imported too many libraries. I didn't exactly know which I really need so I imported the same stuff like the apps, from where I got code fragments, do. But I think that should not be a problem, as long as the needed libraries are there, right?
------------
package com.example.blabla.filetclient;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.iutputStream;
import java.net.Socket;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
Socket socket;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// android.os.Debug.waitForDebugger();
try {
this.socket = new Socket("192.168.178.32", 80);
} catch (IOException e) {
e.printStackTrace();
}
File file = new File(Environment.getExternalStorageDirectory(),
"picture.jpg");
byte[] bytes = new byte[(int) file.length()];
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
bis.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytes.length);
bos.flush();
socket.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
------
The app is supposed to connect to a server and straightly send the file "picture.jpg" which is in the external storage (I am pretty sure that the path is right and that the file really esists there (checked with es file explorer)) and then disconnect.
I did not change the layout, I mean the GUI. I left the original xml file which is from the "Hello world" app untouched, so I expected that "My Application - Hello world!" would come up, doing the job in the background.
But this is what happenes when I run the app on my motorola (not emulator):
First, 0 Gradle errors and warnings. On the phone this alert comes up "filetclient is not responding" and I can click only click on "OK". I can see, that flietclient is running in a white, empty screen, but when I try to bring it to the foreground then that error alert comes again, bringing me back to the desktop.
On server side, nothing comes. No connection attempts. My phone and the server are connected physically 100%, which I can check with other apps.
Can anybody tell me what I did wrong? Why is the code not working and the simple GUI not showing up?
Thank you many times.

marker not display on googlemap

package com.example.sameer.vehicletrackingsystem.Fragments;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.sameer.vehicletrackingsystem.R;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class GoogleMapFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
String add = "Mandhardev";
String state = "Maharashtra";
String country = "India";
String vehicleNumber = "MH-12 FG-1547";
public GoogleMapFragment() {
// Required empty public constructor
}
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_google_map, container, false);
}
@override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.addMarker(new MarkerOptions().position(new LatLng(18.046644, 73.876045)).title(vehicleNumber).snippet(add+", "+state+", "+country));
mMap.getMaxZoomLevel();
mMap.getCameraPosition();
}
}

error: illegal start of type if (myBluetooth == null){

Hello, i am new here and also new in android studio. i have some knowledge in java, c++ but it has some time since that. so i am trying to make an application in order to control a led strip via android. i found a project at instructables that it is very close to what i want to make. the problem is that this project is from 2015. i am trying to troubleshoot the code but i am not so good at it. now it shows me an error here:
error: illegal start of type
if (myBluetooth == null){
^
any thoughts???? Thank you very much!
package com.example.devicelist;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.iutputStream;
import java.util.Set;
import java.util.ArrayList;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
public class DeviceList extends AppCompatActivity implements OnClickListener {
//widgets
private Button btnPaired;
private ListView devicelist;
//bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
private OutputStream outStream = null;
public static String EXTRA_ADDRESS = "device_address";
//if the device has bluetooth
BluetoothAdapter myBluetooth = BluetoothAdapter.getDefaultAdapter();
if (myBluetooth == null){
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if (!myBluetooth.isEnabled()){
//Ask the user to turn on the bluetooth
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}

Categories

Resources