[Q] How to Open New Screen in Android - Android Software Development

Hello All,
I am following this article to learn how to open new screen on button click: http://learnandroid.blogspot.com/2008/01/opening-new-screen-in-android.html
But I am getting 3 error messages like this:
Code:
Description Resource Path Location Type
id cannot be resolved or is not a field screen1.java /screen1/src/test/android line 18 Java Problem
id cannot be resolved or is not a field screen2.java /screen1/src/test/android line 13 Java Problem
Unparsed aapt error(s)! Check the console for output. screen1 line 1 Android ADT Problem
This is what I have done till now:
screen1.java
Code:
package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class screen1 extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.screen1);
Button b = (Button)findViewById(R.id.btnClick);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(screen1.this, screen2.class);
startActivity(i);
}
});
}
}
screen2.java
Code:
package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class screen2 extends Activity
{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.screen2);
Button b = (Button) findViewById(R.id.btnClick2);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();
}
});
}
}
AndroidManifest.xml
Code:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.android">
<application android:icon="@drawable/icon">
<activity class=".Screen1" android:label="Screen 1">
<intent-filter>
<action android:value="android.intent.action.MAIN" />
<category android:value="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity class=".Screen2" android:label="Screen 2">
</activity>
</application>
</manifest>
screen1.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You are in the first Screen"
/>
<Button
id ="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open New Screen"
/>
</LinearLayout>
screen2.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You are in the New Screen"
/>
<Button
id ="@+id/btnClick2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
/>
</LinearLayout>
Please help guys !

To give you an idea, this is screenshot of my project
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}

You have to import the the other class as well. import screen2 in class screen1.
Cmd+Shift+o on mac. probably Ctrl+Shift+o on Windows.

I just tried by placing my cursor on screen1.java
nothing happened ?
and why I am getting those 3 errors ? is it something to do with class ?

Try clicking the "Project -> Clean... -> Select your project -> Click OK" and see if that fixes the problem.

You don't seem to have your resources imported. For example, in my programs, I have "com.package.R" imported. This class links your resources to your java code, and hence it won't find your ID's if you haven't imported it.
Try clean your project (Eclipse is project -> clean, not sure about the others), and see if it then nags you to import it. Otherwise, try manually importing it - it's found under the "gen" folder.
MrP.

try adding "android:" in front of id

Rootstonian said:
try adding "android:" in front of id
Click to expand...
Click to collapse
I think that's the answer. Its supposed to be android:id="@+id/someid"
That and then do a clean build to get R.java to update
From something awesome

killersnowman said:
I think that's the answer. Its supposed to be android:id="@+id/someid"
From something awesome
Click to expand...
Click to collapse
Yes this is correct. Didn't even phase me haha

dolby71 said:
You have to import the the other class as well. import screen2 in class screen1.
Cmd+Shift+o on mac. probably Ctrl+Shift+o on Windows.
Click to expand...
Click to collapse
Not true. screen1 and screen2 are in the same package. As long as the package is defined in each class you don't have to import any classes from that package. And the call to screen2.class is a static call
http://www.programmersheaven.com/mb/java_beginners/288070/288070/import-and-package/
From something awesome

Related

[Q] unable to switch activity

Hi,
I am new to android development. I am facing problem in switching between activities. I am attaching the code files ... Please help me solve this problem
Being a new user the Forum doesn't allow me to write atTheRateSign in my message ... I am replacing it with % sign. Please don't confuse it.
Main Activity:
Code:
package swz.pkg;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class SWMainActivity extends Activity {
/** Called when the activity is first created. */
%Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnMSrch = (Button) findViewById(R.id.btnClosetSearch);
try{
btnMSrch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(),ClosetSearchAct.class);
startActivityForResult(myIntent,0);
}
});
}
catch (Exception ex)
{
System.out.println("---------------------******------------------------");
ex.printStackTrace();
System.out.println();
System.out.println("---------------------******------------------------");
}
}
}
main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="%+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="ht ... android"
>
<Button
android:id="%+id/btnMeasurementSearch"
android:layout_width="fill_parent"
android:layout_height="150px"
android:background="#ffffffff"
android:text="Measurement Search"
android:textSize="26sp"
android:typeface="serif"
android:textStyle="bold"
android:textColor="#ff8c2528"
android:layout_x="0px"
android:layout_y="47px"
>
</Button>
<Button
android:id="%+id/btnClosetSearch"
android:layout_width="fill_parent"
android:layout_height="150px"
android:text="Closet Search"
android:textSize="26sp"
android:typeface="serif"
android:textStyle="bold"
android:textColor="#ff462556"
android:layout_x="0px"
android:layout_y="213px"
>
</Button>
</AbsoluteLayout>
closetSearch activity(The next activity I want to move to):
Code:
package swz.pkg;
import android.app.Activity;
import android.os.Bundle;
public class ClosetSearchAct extends Activity {
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.closetsearchact);
}
}
closetsearchact.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="%+id/widget1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="ht .... android"
>
<Spinner
android:id="%+id/spinner1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="0px"
android:layout_y="33px"
>
</Spinner>
<Spinner
android:id="%+id/spinner2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="0px"
android:layout_y="101px"
>
</Spinner>
<Spinner
android:id="%+id/spinner3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="0px"
android:layout_y="173px"
>
</Spinner>
<ImageButton
android:id="%+id/btnReg"
android:layout_width="128px"
android:layout_height="wrap_content"
android:src="%drawable/reg"
android:layout_x="151px"
android:layout_y="279px"
>
</ImageButton>
<ImageButton
android:id="%+id/btnSearch"
android:layout_width="114px"
android:layout_height="49px"
android:src="%drawable/search"
android:layout_x="37px"
android:layout_y="279px"
>
</ImageButton>
</AbsoluteLayout>
AndroidManifest.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="ht ... android"
package="swz.pkg"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="%drawable/icon" android:label="%string/app_name">
<activity android:name=".SWMainActivity"
android:label="%string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ClosetSearchAct" android:label="%string/app_name"> </activity>
</application>
</manifest>

Need Help With Admob Ads

for the life of me i cannot get the ads to display. i have it all set so it shows the space for them, but tit will not display an ad. my code is posted below
java file
Code:
package com.cmoney12051.helpcenter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Random;
import com.facebook.android.*;
import com.facebook.android.Facebook.*;
import com.google.ads.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class WebViewTemplate extends Activity {
private WebView myWebView;
/** Called when the activity is first created. */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) { // Enables browsing to previous pages with the hardware back button
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Lookup R.layout.main
AdView layout = (AdView)findViewById(R.id.ads);
// Create the adView
// Please replace MY_BANNER_UNIT_ID with your AdMob Publisher ID
String pubID ="xxxxxxxxxxxxxxx";
AdView adView2 = new AdView(this, AdSize.BANNER, pubID );
// Add the adView to it
layout.addView(adView2);
// Initiate a generic request to load it with an ad
AdRequest request= new AdRequest();
request.setTesting(true);
adView2.setVisibility(AdView.VISIBLE);
adView2.loadAd(request);
myWebView = (WebView) findViewById(R.id.webview); // Create an instance of WebView and set it to the layout component created with id webview in main.xml
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://cmoney12051.com/HelpCenter/mobile.php"); // Specify the URL to load when the application starts
//myWebView.loadUrl("file://sdcard/"); // Specify a local file to load when the application starts. Will only load file types WebView supports
myWebView.setWebViewClient(new WebViewKeep());
myWebView.getSettings().setBuiltInZoomControls(true); // Initialize zoom controls for your WebView component
myWebView.getSettings().setUseWideViewPort(true); // Initializes double-tap zoom control
}
private class WebViewKeep extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuItem item = menu.add("Login");
item.setIcon(R.drawable.login);
item = menu.add("Register");
item.setIcon(R.drawable.register);
item = menu.add("Email Cmoney");
item.setIcon(R.drawable.email);
item = menu.add("Share on Facebook");
item.setIcon(R.drawable.facebook_icon);
item = menu.add("Donate");
item.setIcon(R.drawable.donate);
item = menu.add("Exit");
item.setIcon(R.drawable.exit);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getTitle() == "Exit"){
android.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Exit?");
builder.setIcon(R.drawable.exit);
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
System.exit(0);
}
});
builder.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
if (item.getTitle() == "Login"){
myWebView.loadUrl("http://cmoney12051.com/HelpCenter/ucp.php?mode=login");
myWebView.setWebViewClient(new WebViewKeep());
}
if (item.getTitle() == "Register"){
myWebView.loadUrl("http://cmoney12051.com/HelpCenter/ucp.php?mode=register");
myWebView.setWebViewClient(new WebViewKeep());
}
if (item.getTitle() == "Email Cmoney"){
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
String aEmailList[] = { "[email protected]" };
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, aEmailList);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "A Message From Cmoneys Android Help Center App");
emailIntent.setType("plain/text");
startActivity(Intent.createChooser(emailIntent, "Send your email in:"));
}
if (item.getTitle() == "Share on Facebook"){
myWebView.loadUrl("http://www.facebook.com/sharer.php?u=http://cmoney12051.com/HelpCenter&t=Cmoneys%20Android%20Help%20Center&refsrc=http://m.facebook.com/sharer.php");
myWebView.setWebViewClient(new WebViewKeep());
}
if (item.getTitle() == "Donate"){
myWebView.loadUrl("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GDB6U44B67FXU");
myWebView.setWebViewClient(new WebViewKeep());
}
return true;
}
}
Main.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.google.ads.AdView
android:layout_width="fill_parent"
android:layout_height="60px"
android:layout_alignParentTop="true"
android:visibility="visible"
android:id="@+id/ads">
</com.google.ads.AdView>
<TableRow android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tableRow1">
<ImageView android:id="@+id/logo"
android:src="@drawable/logo"
android:layout_height="wrap_content"
android:layout_width="wrap_content">
</ImageView>
<TextView android:text="Cmoneys Android Help Center"
android:id="@+id/textView1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textStyle="bold"
android:textSize="30px">
</TextView>
</TableRow>
<DigitalClock android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/digitalClock1" android:text="DigitalClock"></DigitalClock>
<WebView
android:id="@+id/webview"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:focusableInTouchMode="true">
</WebView>
</LinearLayout>
Manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="2"
android:versionName="1.1" package="com.cmoney12051.helpcenter">
<application android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar" android:icon="@drawable/logo">
<activity android:name=".WebViewTemplate"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdView"
android:configChanges="keyboard|keyboardHidden|orientation"/>
<meta-data android:value="xxxxxxxxxxxxxx" android:name="pubID" />
<meta-data android:value="true" android:name="AD_REQUEST" />
<meta-data android:value="false" android:name="TEST_MODE" />
</application>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
</manifest>
Any Help Is Really Appreciated. Thanks anyway

Assistance with zRam configuration

I am the developer of the Bionx Catalsyt rom for the Droid Razr and I need some assistance with my toolkit I have developed for my rom (Its open sourced if youd like to contribute) I am relatively new to android app develoment so bare with me.
I need some assistance with zRAM configurations or a dev with some experience with it. I needed zRAM configurations for optimizing kernel usage on the Droid Razr to improve performance so I Ported the zRAM configurations from the CM10 Android Settings in my toolkit which led to me bringing over the Android System Properties (Reflected) and Utils Class for it to function correctly. 2 options are available to users. Configuration which gives users 4 options to choose from (disabled, 10%, 18%, 26%) and the option to enable zRAM or "Purge Memory". When I set a value, it seems not to "stick" or take affect but toggling Purge Settings does take affect. If i looked at a logcat, what values or what exactly would i be searching for to correct this feature or make sure it is taking affect or working at all?
and can any dev take a look at the code and see if I screwed anything up or miss writ something. (I didnt really change anything when it came from cm10, just wanting to port it to be useable on a stock based rom or AOSP)
Source
https://github.com/rgocal/app_packages_BionxDashboard.git
src/com/android/ZRAMconfig is the located class
src/android/os/ is location of imports needed
First, keep in mind you need a kernel with zRam support for those settings to work.
To set the zRam compression to the desired level (let's take 64mb as an example), you want to do something like this in a terminal :
Code:
su
busybox mkswap /dev/block/zram0
busybox swapon /dev/block/zram0
echo $((1024*1024*64)) > /sys/block/zram0/disksize [COLOR="Green"]// Replace 64 with the desired compression level[/COLOR]
So in java, this would translate to something like this :
A simple layout with an EditText for the user to input the desired zRam compression level & a Button to apply the value :
zram.xml
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/userInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="48dp"
android:layout_marginRight="48dp"
android:layout_marginTop="32dp"
android:ellipsize="end"
android:hint="Enter zRam Compression Level"
android:inputType="number" />
<Button
android:id="@+id/apply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="8dp"
android:text="Apply"
android:textColor="#33b5e5" />
</LinearLayout>
The corresponding java Class :
Zram.java
Code:
package com.rgocal.zram.settings;
import java.io.DataOutputStream;
import java.io.IOException;
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.EditText;
import android.widget.Toast;
public class Zram extends Activity implements OnClickListener {
private EditText input;
private Button apply;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.zram);
input = (EditText) findViewById(R.id.userInput);
apply = (Button) findViewById(R.id.apply);
apply.setOnClickListener(this);
}
@Override
public void onClick(View v) {
int value = Integer.parseInt(input.getText().toString());
// Arbitrary value, I don't know the maximum zRam compression (if
// there's one)
if (value > 200) {
Toast.makeText(
this,
"The value you entered is too high and may cause problems! Please reduce it",
Toast.LENGTH_SHORT).show();
} else {
try {
Process process = null;
process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(
process.getOutputStream());
os.writeBytes("busybox mkswap /dev/block/zram0" + "\n");
os.writeBytes("busybox swapon /dev/block/zram0" + "\n");
os.writeBytes("echo $((1024*1024*" + value
+ ")) > /sys/block/zram0/disksize" + "\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
Log.v("zRam", "Compression level set to " + value);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Your AndroidManifest.xml :
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.rgocal.zram.settings.Zram"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="zRam Settings"
android:theme="@style/AppTheme" >
<activity
android:name="com.rgocal.zram.settings.Zram"
android:label="zRam Settings" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The resulting apk : http://168.144.134.166/downloads/zRamSettings.apk
Screenshot :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
I uploaded the full code on my github to make it easier for you to grab it : https://github.com/Androguide/zRamSettings
Hope this gets you going, good luck
Androguide.fr said:
First, keep in mind you need a kernel with zRam support for those settings to work.
[*]The resulting apk : http://168.144.134.166/downloads/zRamSettings.apk
[*]Screenshot :
[/LIST]
I uploaded the full code on my github to make it easier for you to grab it : https://github.com/Androguide/zRamSettings
Hope this gets you going, good luck
Click to expand...
Click to collapse
Like a boss! Thanks!
Our kernel supports zRAM configurations with limitation but with Kexec support, we have more options so I needed some options for both ways
Update: Integrated this activity as a preference screen in my current zRAM configurations so now I have support both ways. Noticed your comment of how we dont know how to calculate a max/min RAM value so I'm looking for that value currently. Now all I need is to find a way to allow the activity to detect whether or not the device supports zRAM configurations and prevent the user from having this options if it isnt so it doesnt apply blank values.

[GUIDE][NOOB Friendly][HOW-TO]Simple Calculator App

HOW-To Make A Simple Android Calculator​
How To Make A Simple Calculator
Step 1
. Select Create New Android Application
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Creating XML For Layout
To create a calculator first we need to create the layout of the calculator.
Layout is created using XML file given below
Copy This To Your “activity_main” (Note- If you named the layout activity main or something else please change it to activity_main or it will give a couple of errors)
Code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="@+id/result_id"
android:layout_width="fill_parent"
android:layout_height="120dp"
/>
<Button
android:id="@+id/Btn7_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:text="7"
android:onClick="btn7Clicked"
/>
<Button
android:id="@+id/Btn8_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn7_id"
android:text="8"
android:onClick="btn8Clicked"
/>
<Button
android:id="@+id/Btn9_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn8_id"
android:text="9"
android:onClick="btn9Clicked"
/>
<Button
android:id="@+id/Btnclear_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/result_id"
android:layout_toRightOf="@id/Btn9_id"
android:text="clear"
android:onClick="btnclearClicked"
/>
<Button
android:id="@+id/Btn4_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn7_id"
android:text="4"
android:onClick="btn4Clicked"
/> <Button
android:id="@+id/Btn5_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn8_id"
android:layout_toRightOf="@id/Btn4_id"
android:text="5"
android:onClick="btn5Clicked"
/> <Button
android:id="@+id/Btn6_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn9_id"
android:layout_toRightOf="@id/Btn5_id"
android:text="6"
android:onClick="btn6Clicked"
/>
<Button
android:id="@+id/Btnplus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnclear_id"
android:layout_toRightOf="@id/Btn6_id"
android:text="+"
android:onClick="btnplusClicked"
/>
<Button
android:id="@+id/Btn1_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn4_id"
android:text="1"
android:onClick="btn1Clicked"
/>
<Button
android:id="@+id/Btn2_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn5_id"
android:layout_toRightOf="@id/Btn1_id"
android:text="2"
android:onClick="btn2Clicked"
/>
<Button
android:id="@+id/Btn3_id"
android:layout_width="70dp"
android:layout_height="60dp"
android:layout_below="@id/Btn6_id"
android:layout_toRightOf="@id/Btn2_id"
android:text="3"
android:onClick="btn3Clicked"
/>
<Button
android:id="@+id/Btnminus_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnplus_id"
android:layout_toRightOf="@id/Btn3_id"
android:text="-"
android:onClick="btnminusClicked"
/>
<Button
android:id="@+id/Btnequal_id"
android:layout_width="110dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:text="="
android:onClick="btnequalClicked"
/>
<Button
android:id="@+id/Btndivide_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btn1_id"
android:layout_toRightOf="@id/Btnequal_id"
android:text="/"
android:onClick="btndivideClicked"
/>
<Button
android:id="@+id/Btnmulti_id"
android:layout_width="90dp"
android:layout_height="60dp"
android:layout_below="@id/Btnminus_id"
android:layout_toRightOf="@id/Btndivide_id"
android:text="*"
android:onClick="btnmultiClicked"
/>
</RelativeLayout>
The Graphical Layout Will look Like this
Then You have to Make The Buttons work and calculate your numbers
Simply find your MainActivity.java (It Is place under package name)
Copy This to your java file :
Code:
package com.dc.simplecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
public String str ="";
Character op = 'q';
int i,num,numtemp;
EditText showResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showResult = (EditText)findViewById(R.id.result_id);
}
public void btn1Clicked(View v){
insert(1);
}
public void btn2Clicked(View v){
insert(2);
}
public void btn3Clicked(View v){
insert(3);
}
public void btn4Clicked(View v){
insert(4);
}
public void btn5Clicked(View v){
insert(5);
}
public void btn6Clicked(View v){
insert(6);
}
public void btn7Clicked(View v){
insert(7);
}
public void btn8Clicked(View v){
insert(8);
}
public void btn9Clicked(View v){
insert(9);
}
public void btnplusClicked(View v){
perform();
op = '+';
}
public void btnminusClicked(View v){
perform();
op = '-';
}
public void btndivideClicked(View v){
perform();
op = '/';
}
public void btnmultiClicked(View v){
perform();
op = '*';
}
public void btnequalClicked(View v){
calculate();
}
public void btnclearClicked(View v){
reset();
}
private void reset() {
// TODO Auto-generated method stub
str ="";
op ='q';
num = 0;
numtemp = 0;
showResult.setText("");
}
private void insert(int j) {
// TODO Auto-generated method stub
str = str+Integer.toString(j);
num = Integer.valueOf(str).intValue();
showResult.setText(str);
}
private void perform() {
// TODO Auto-generated method stub
str = "";
numtemp = num;
}
private void calculate() {
// TODO Auto-generated method stub
if(op == '+')
num = numtemp+num;
else if(op == '-')
num = numtemp-num;
else if(op == '/')
num = numtemp/num;
else if(op == '*')
num = numtemp*num;
showResult.setText(""+num);
}
}
Next Step!
Testing Your App, Fingers Crossed
Simply Click On Run>Run As Android Application
Congo! You Just Made A Simple Calc App……
Exporting Your App
Open Android Manifest.xml
Select use Export Wizard
That’s All….
If you have any queries post in this thread I will try my best to solve it…
Sucess!
Have A Good Day!
​
Reserved

[Tutorial] Learn to parse HTML Pages on Android with JSoup

Hello,
I create that thread to offer you a tutorial learning you to parse HTML pages on Android by using the JSoup Library. You can also discover this tutorial in video on Youtube :
When you make Android applications, you can have to parse HTML data or HTML pages got from the Web. One of the most known solution to make that in Java is to use JSoup Library. Like said on the official website of JSoup : "It is a Java library for working with real-world HTML. It provides a very convenient API for extracting and manipulating data, using the best of DOM, CSS, and jquery-like methods."
JSoup can be used in Android applications and we're going to study how to parse an HTML Page on Android with JSoup.
First, you need to add the JSoup dependency in your Gradle build file :
Code:
compile 'org.jsoup:jsoup:1.10.1'
For our example, we are going to download the content of the SSaurel's Blog and display all the links of the main page. To download the content of a website, JSoup offers the connect method and then a get method. This last method works synchronously. So, we should call these methods in a separated Thread. Our application will have just a simple layout with a Button to launch the download of the website and a TextView to display the links.
It will have the following form :
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.ssaurel.jsouptut.MainActivity">
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get website"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"/>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result ..."
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:layout_below="@id/getBtn"
android:textSize="17sp"/>
</RelativeLayout>
In the main Activity of the application, we are going to get instances of the Button and the TextView from our layout. Then, we set a click listener on the Button to start the download of the website when the user will click it.
In the getWebsite() method, we create a new Thread to download the content of the website. We use the connect() method of the Jsoup object to connect the application to the website, then we call the get() method to download the content. These calls return a Document object instance. We have to call the select() method of this instance with the query to get all the links of the content. This query returns an Elements instance and finally, we have just to iterate on the elements contained in this object to display the content of each link to the screen.
At the end of our separated Thread, we refresh the UI with the links got from the website. This refresh is embedded inside a runOnUiThread call because it's forbidden to refresh the UI elements inside a separated thread.
The code of the MainActivity has the following form :
Code:
package com.ssaurel.jsouptut;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
private Button getBtn;
private TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getWebsite();
}
});
}
private void getWebsite() {
new Thread(new Runnable() {
@Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
String title = doc.title();
Elements links = doc.select("a[href]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("href"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
}
Last step is to run the application and to enjoy the final result with all the links of the SSaurel's blog displayed on the screen :
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Don't hesitate to try JSoup on your Android application and give me your feedbacks on this tutorial.
Thanks.
Sylvain

Categories

Resources