Android App Help - Android Q&A, Help & Troubleshooting

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

Related

[Q] Creating Translator App

Hi all, ive just started lookin up to Java and creating app, i know i should start and improove slowly, but i need quickly some helps with makin a Translator.apk using Bing API translator, cause google one are now only aviable if u pay them.
i saw a litle exemple where i downloaded the Jar file(which i put it in /libs and mine came out like this:
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText in, out;
Button trns;
String inPut;
@Override
protected void onCreate() {
// TODO Auto-generated method stub
Translate.setClientId("hidden");
Translate.setClientSecret("hidden");
super.onCreate();
setContentView(R.layout.activity_main);
trns = (Button) findViewById(R.id.button1);
in = (EditText) findViewById(R.id.editText1);
out = (EditText) findViewById(R.id.editText2);
inPut = in.getText().toString();
trns.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
String translatedText = Translate.execute(inPut, Language.GERMAN,
Language.FRENCH);
out.setText(translatedText);
} catch (Exception e) {
e.printStackTrace();
}
}
}
problaby its all wrong i know, thats why i need help
Guess i have to add Internet permission to the manifest(how ? and do i have to make some controll after?)
I studied at school some basic C# so im used to the grouBox which i didnt find with eclipse. What's the nearest thing with it where i can put a list of all selectable language to translate?
Hope somebody could help me, ty

[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

[Q] Runtime.getRuntime().exec dosn't work

Hi i'm trying to make an app with a button that free cache of the phone.. This is the code:
Code:
package com.mkyong.android;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import com.example.toast.R;
public class MainActivity extends Activity {
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@SuppressLint("SdCardPath")
@Override
public void onClick(View arg0) {
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su -c 'echo 3 > /proc/sys/vm/drop_caches'");
Toast.makeText(MainActivity.this, "Script lanciato con `successo, memoria svuotata.", Toast.LENGTH_LONG).show();`
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Well i've got no errors but nothing happen.. When i press the button the free ram memory rest the same. (to see the free memory i open the terminal emulator and i write the "free" command"). Someone can help me? What's wrong?

[Q] Some problem with my code

Hi, I having some problem with this simple code. I don't undestrand because ADT impost fields as EditText, TextView and Button as field final. I think that there' some errore in my code, I admit that is one of my first times that i programming for andoird, so have patience with me.
I apologize if I wrong section :silly:
That's my code:
package com.example.buttoncerca;
import android.os.Bundle;
import android.app.Activity;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RisponditoreInterattivoActivity extends Activity implements Lista {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_risponditore_interattivo);
final EditText text = (EditText)this.findViewById(R.id.campoNome);
Button button = (Button)this.findViewById(R.id.buttone);
final TextView tv = (TextView)this.findViewById(R.id.testoSaluto);
button.setOnClickListener(new OnClickListener(){
public void onClick(View arg0){
Editable nome = text.getText();
String s = nome.toString();
for(int c =0; c<3; c++){
if(toppings[c].equals(s)){
tv.setText(toppings[c] + " si butta nel " + cestino[c]);
} //End if
}//End for
}//End onClick
});
}
}
Click to expand...
Click to collapse
I implements inteface Lista, this is code:
package com.example.buttoncerca;
public interface Lista {
String[] toppings = {"Plastica", "Legno", "Cartone"};
String[] cestino = {"Cestino plastica", "Cestino legno", "Cestino cartone"};
}
Click to expand...
Click to collapse
And... what's the problem? Please post it "as is".
You need to instantiate the editable first, with BUFFERTYPE.EDITABLE, because in your current case you are casting a charseq to an editable so that's likely the exception you are getting (hard to know without a logcat). See here:
http://developer.android.com/reference/android/widget/EditText.html#getText()
Sent from my Amaze 4G using xda app-developers app

[Q] App doesn't get site source code

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

Categories

Resources