Archive for the ‘Android’ Category

Testing for Writing Code

Posted: April 28, 2013 in Android


package com.test.guide;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

/**
* Android µœ÷◊Û”“ª¨∂Ø÷∏“˝–ßπ˚
* @Description: Android µœ÷◊Û”“ª¨∂Ø÷∏“˝–ßπ˚

* @File: MyGuideViewActivity.java

* @Package com.test.guide

* @Author Hanyonglu

* @Date 2012-4-6 œ¬ŒÁ11:15:18

* @Version V1.0
*/
public class MyGuideViewActivity extends Activity {
private ViewPager viewPager;
private ArrayList pageViews;
private ImageView imageView;
private ImageView[] imageViews;
// ∞¸π¸ª¨∂ØÕº∆¨LinearLayout
private ViewGroup main;
// ∞¸π¸–°‘≤µ„µƒLinearLayout
private ViewGroup group;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// …Ë÷√Œfi±ÍÂ¥∞ø⁄
requestWindowFeature(Window.FEATURE_NO_TITLE);

LayoutInflater inflater = getLayoutInflater();
pageViews = new ArrayList();
pageViews.add(inflater.inflate(R.layout.item05, null));
pageViews.add(inflater.inflate(R.layout.item06, null));
pageViews.add(inflater.inflate(R.layout.item01, null));
pageViews.add(inflater.inflate(R.layout.item02, null));
pageViews.add(inflater.inflate(R.layout.item03, null));
pageViews.add(inflater.inflate(R.layout.item04, null));

imageViews = new ImageView[pageViews.size()];
main = (ViewGroup)inflater.inflate(R.layout.main, null);

group = (ViewGroup)main.findViewById(R.id.viewGroup);
viewPager = (ViewPager)main.findViewById(R.id.guidePages);

for (int i = 0; i < pageViews.size(); i++) {
imageView = new ImageView(MyGuideViewActivity.this);
imageView.setLayoutParams(new LayoutParams(20,20));
imageView.setPadding(20, 0, 20, 0);
imageViews[i] = imageView;

if (i == 0) {
//ƒ¨»œ—°÷–µ⁄“ª’≈Õº∆¨
imageViews[i].setBackgroundResource(R.drawable.page_indicator_focused);
} else {
imageViews[i].setBackgroundResource(R.drawable.page_indicator);
}

group.addView(imageViews[i]);
}

setContentView(main);

viewPager.setAdapter(new GuidePageAdapter());
viewPager.setOnPageChangeListener(new GuidePageChangeListener());
}

// ÷∏“˝“≥√Ê ˝æ›  ≈‰∆˜
class GuidePageAdapter extends PagerAdapter {

@Override
public int getCount() {
return pageViews.size();
}

@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}

@Override
public int getItemPosition(Object object) {
// TODO Auto-generated method stub
return super.getItemPosition(object);
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
// TODO Auto-generated method stub
((ViewPager) arg0).removeView(pageViews.get(arg1));
}

@Override
public Object instantiateItem(View arg0, int arg1) {
// TODO Auto-generated method stub
((ViewPager) arg0).addView(pageViews.get(arg1));
return pageViews.get(arg1);
}

@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
// TODO Auto-generated method stub

}

@Override
public Parcelable saveState() {
// TODO Auto-generated method stub
return null;
}

@Override
public void startUpdate(View arg0) {
// TODO Auto-generated method stub

}

@Override
public void finishUpdate(View arg0) {
// TODO Auto-generated method stub

}
}

// ÷∏“˝“≥√Ê∏¸∏ƒ ¬º˛º‡Ã˝∆˜
class GuidePageChangeListener implements OnPageChangeListener {

@Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub

}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub

}

@Override
public void onPageSelected(int arg0) {
for (int i = 0; i < imageViews.length; i++) {
imageViews[arg0].setBackgroundResource(R.drawable.page_indicator_focused);

if (arg0 != i) {
imageViews[i].setBackgroundResource(R.drawable.page_indicator);
}
}
}
}
}

Android Mysql

Posted: October 14, 2012 in Android

Android <=> Mysql

Main.java

——————————————

package com.example.databasetest_1;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

private EditText email;
private EditText pwd;
private Button submit;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

email = (EditText)findViewById(R.id.editTextEmail);
pwd = (EditText)findViewById(R.id.editTextPassword);
submit = (Button)findViewById(R.id.buttonSubmit);

submit.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

try{
Toast.makeText(getApplicationContext(), “test”, Toast.LENGTH_SHORT).show();
Map<String, String> map = new HashMap<String, String>();
String emailString = email.getText().toString();
String pwdString = pwd.getText().toString();
map.put(“email”, emailString);
map.put(“pwd”, pwdString);
boolean result = submitDataByHttpClientDoPost(map, “http://10.0.2.2/android_con.php&#8221;);

if(result) {
Toast.makeText(getApplicationContext(), “Data Inserted.”, Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), “Failed”, Toast.LENGTH_SHORT).show();
}
}
catch(Exception e){
e.printStackTrace();
System.out.println(e.getMessage());
}
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

public Boolean submitDataByHttpClientDoPost(Map<String, String> map, String path) throws Exception {

HttpClient hc = new DefaultHttpClient();

HttpPost request = new HttpPost(path);

List<NameValuePair> parameters = new ArrayList<NameValuePair>();

for(Map.Entry<String, String> entry:map.entrySet()) {
NameValuePair nvp = new BasicNameValuePair(entry.getKey(), entry.getValue());
parameters.add(nvp);
}

HttpEntity entity = new UrlEncodedFormEntity(parameters, “UTF-8”);

request.setEntity(entity);

HttpResponse response = hc.execute(request);

if(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
return true;
}
else {
return false;
}
}
}

 

main.xml

—————————————–

<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
xmlns:tools=”http://schemas.android.com/tools&#8221;
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:orientation=”vertical” >

<EditText
android:id=”@+id/editTextEmail”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:ems=”10″
android:hint=”Email” >

<requestFocus />
</EditText>

<EditText
android:id=”@+id/editTextPassword”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:ems=”10″
android:hint=”Password”
android:inputType=”textPassword” />

<Button
android:id=”@+id/buttonSubmit”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:text=”Submit” />

</LinearLayout>

 

android_con.php

——————————————

<?php

$con = mysql_connect(“localhost”, “root”, “password”);

if(!$con) {
die(‘Could not connect: ‘.mysql_connect);
}
else {

mysql_select_db(“database”, $con);

//get the android sending data
$str_email = $_REQUEST[“email”];
$str_pwd = $_REQUEST[“pwd”];
$sql = “insert into users(email, password) values(‘”.$str_email.”‘, ‘”.$str_pwd.”‘)”;

//insert data to database
if(!mysql_query($sql,$con)) {
return false;
}
else {
return true;
}

//close connection
mysql_close($con);

}

?>

 

Mainfest.xml

———————————–

<manifest xmlns:android=”http://schemas.android.com/apk/res/android&#8221;
package=”com.example.databasetest_1″
android:versionCode=”1″
android:versionName=”1.0″ >

<uses-sdk
android:minSdkVersion=”8″
android:targetSdkVersion=”15″ />
<uses-permission android:name=”android.permission.INTERNET”/>

<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”.MainActivity”
android:label=”@string/title_activity_main” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

 

 

Very Clear [ Android <=> Mysql ], no explain more, type again then u also can find out!

Introduction:

In some developer books, we know that Android is support XML. But supporting XML is really meaningful? And why we need to use XML – based Layouts? Here is your answer.

1. Before we start, we should know what is XML – Based Layout. Actually, XML – Based Layout is a format which is made up by several parts. They are the Specifical widgets’ containers. If you have any experience about HTML, you will know how it looks like.  It looks like a tree, the containers are the elements of  the tree.

2. Alright, next is why we should use that? In the book (Beginning Android), it’s described:

Most everything you do using XML layout files can be acieved through Java code. For example, you could use setTypeface() to have a button render its text in bold, instead of using a property in an XML layout. Since XML layouts are yet another file for you to keep track of, we need good reasons for using such files.

From these words, we know that by using XML – Based Layouts can help us for programming. In fact, most UI is made up by the similar format as XML. Such as, XUL, XAML, HTML, and so on.

3. The next is our topic. What’s the difference between using XML – Based Layouts and not using.

Did you remember the previous sample of Now. We using that to compare the differences.

I show you the coding without using XML – Based Layouts:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

package com.android.Now;

import android.app.Activity;  // If you want to creat an Activity, must have this.
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;

public class Now extends Activity implements View.OnClickListener {
    Button btn;
 
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        btn=new Button(this);
        btn.setOnClickListener(this);
        updateTime();
        setContentView(btn);
    }
    
    public void onClick(View view){
     updateTime();
    }
    
    public void updateTime(){
     btn.setText(new Date().toString());
    }   
}

After finish coding, we try to run AVD. This was the one that I used in DAY-3.

=====================================================

Now, using XML -Based Layouts. Coding:

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

package com.android.Now_xml; //Create a new project and new app, named “Now_xml”

import android.app.Activity; 
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.util.Date;

public class Now_xml extends Activity implements View.OnClickListener {
    Button btn;
 
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

       setContentView(R.layout.main); //There is  difference.
        
        btn=(Button) findViewById(R.id.button); //There also is difference.
        btn.setOnClickListener(this);
        updateTime();
    }
    
    public void onClick(View view){
     updateTime();
    }
    
    public void updateTime(){
     btn.setText(new Date().toString());
    }   
}

=============================================

But, finally display is the same.

 

Maybe someone will ask, but you didn’t use the XML. Yes, these just Java coding. And, only has these coding, cant run the program. We should edit something, that’s Layout.

I showed you the picture that is at the beginning of the blog, was the Layout without editing. So how to edit? We should find the correct place:

We find the main.xml of folder “layout”. We should do the following: (Change the xml coding to these)

And also don’t forget “Ctrl+S”, save the file. Now, you can run the AVD.

==========================================================

android:id —— anything you want to use in your java source needs it.

android:text —— indicates the intial text to be displayed on the button

android:layout_width and android:layout_height —– tell Android to have the button’s width and height fill the parent.

Now, I think you have already know what’s the difference by using XML – Based Layouts.

Hope you understand, and thanks for reading.

Introduction:

In some OS, such as Window. When you want to run a program, before you close the program, the program still is running. There, the program is closed by the user or programmer who define the time to close the program. But Android still like that way to stop its program, or having other way?

1. The first thing, is we should know what is Activity.

In SAMS book ( Teach yourself in 24 hours), We find that” The Activity class is central to every Android application. Much of the time, you’ll define and implement an activity for each screen in your application.” Each screen is most important key word.

Activity is the centre component of Android program. Now, let’s see the relations with each other.

There, as we can see, the Activity just a subset of Context . (Maybe, you will ask what does context used for? The context is used to show the program on your screen.)

2. The basic function of cell phone is call. So, the calling is the highest priority. If a call coming, the system should pause the running program. If the phone’s bettery is lower, the system will pause or stop the rest program which is waiting at foreground. So specify to the Activity, its life depends on the system, not user or programmer.

Now, let’s go to our topic. At first, we should understand an Activity Lifecycle diagram.

From the diagram, we can see the 3 colors which are represented “Start”, “running”, “shut down” and “killed”. When we want to run an Activity, the activity will start firstly.  When the activity running, the user can see it (the activity which stated just now) on the screen. If right now, another new activity starts or comes (such as a tip box shows up), the user still can see the last activity, but cannot interact with, there is Pause. If the last activity is hidden by the new activity, cannot see the screen (there, means the old activity is completely covered by the new activity) any more,  it’s stop. If the activity is killed by the system or never started, it’s killed.

3. How does Android control or manage the Activities?

The Android system using  Activity stack to manage them. For example, there are 4 layers in the stack.

A, B, C, D.

The running activity is the highest priority activity which is on the top of the stack. When the new activity comes, the top activity will go to the second layer. If still can see it (the second activity), it’s pause. If cannot see, it’s stop. If the phone doesn’t have enough space or resource to keep the second activity exist, it’s gonna be killed (normally, the lowest one is closed first) . All of layers obey above.

4. Maybe you still have some questions want to ask. As we know, the android phone screen can be fliped. It means the activity will adapt the new screen size. So, how does activity work now?

Okay, actually, the Android will pause the activity, then stop it, and destroy it. Next, it will creat agian, start and resume the activity.

From these, we can see that, the activity life is not managed by user, but Android system.

Thank for reading.

[ Android ] DAY-3 New App-Time(Now)

Posted: January 11, 2011 in Android

Today, I write a new Android App, here is the cutscreen:

As you can see, it show the time and date.

Okay!

There, I put the downloading link, for you to try and debug this application.

Android Emulator is a virtual mobile that is packaged along with the Android SDK. It runs on your computer and can be used to prototype, develop and test applications without having to buy a physical device. Almost all of the hardware and software features of a typical mobile device are mimicked in the Android emulator. However, if you want to try out some apps from the Android market, you can’t do that with the emulator as it does not include ‘Android market’. Here is a step-by-step guide to enable Android market in the emulator.

Steps to enable Android market in the emulator

1. Download and install the latest Android SDK (Android 2.2, API 8, revision 2) from here. This comes up with all the tools needed for development and testing of your application. Make sure the driver ‘ADB interface’ is installed on your machine. In most of the cases, the driver will be installed directly once you plug-in the device. [The SDK installation location will be referred to as SDK_LOCATION in the rest of the article]

2. Next step is to create a Android Virtual Device. Select ‘Virtual Devices’ from the left pane of the Android SDK and AVD Manager. Create a new virtual device with the details mentioned in the screenshot below. The screen might be frozen for few minutes while the virtual device is being created.

 

3. After the device is created, go to the location ‘%userprofile%/.android/avd’. You will find a folder named ‘DemoDevice.avd’. Copy the system image ‘system,img’ from ‘SDK_LOCATION/platforms/android-8/images’ to the folder ‘DemoDevices.avd’.

4. Start the emulator specifying the partition size. From cmd: emulator –avd DemoDevice –partition-size 100. (100 MB will be allotted for user space). Emulator opens up and it looks like the one below. Note: If the command emulator is not recognized, add SDK_LOCATION/tools to the PATH variable.

5. From cmd, execute ‘adb pull /system/build.prop .’. This will copy the file build.prop to your current working directory. Open it with your favorite text editor and change the property ‘ro.config.nocheckin=yes’. This is needed to fix the freezing of market downloads. Related article.

6. Now, we have to push back the modified build.prop. This is not as easy as pulling it out. First, you have to mount the /system partition in read-write mode. Check out this to know how to do that. After the partition is remounted, execute the adb push command to push back the build.prop ‘adb push build.prop /system/.

7. The next thing is to install the Market application. Download ‘Vending.apk’ from this thread. Google Services framework is a pre-requisite for Android market. To get ‘GoogleServicesFramework.apk’, download upload.zip from here and extract the zip to find the .apk file inside /system/app. Push both these .apk to the device. ‘adb push Vending.apk /system/app/.’ ‘adb push GoogleServicesFramework.apk /system/app/.’. Also, delete the  SdkSetup.apk from the device. ‘adb shell rm /system/app/SdkSetup.apk’. Make sure the SdkSetup.apk is deleted otherwise the emulator will be reverted back to its original stage.

8. Close the emulator. Delete the images userdata.img, userdata-qemu.img and cache.img from ‘%userprofile%/.android/avd/DemoDevice.avd’. Start the emulator again from Android SDK and AVD Manager. Android Market will be available on the emulator now. On opening the market, you will be prompted to connect with your Google account. Connect with your Google account and install your favorite apps on the emulator.

 

Note: Installation of apps from Android market seems to be very slow in the emulator. Market app crashed couple of times before I get the chance to install the apps. Also, I could not find the most popular Android game ‘Angry Birds’ in the market. Installing the same from its .apk didn’t work either. I am trying to tweak the emulator to make it work smoothly with Android Market. If you have any tips for the same, please post them as comments here.

Update: Uttam Hoode has tried this approach with Android 2.3 SDK and it worked fine. 

 
 

Artical from: http://blog.varunkumar.me/2010/11/how-to-install-android-market-in-google.html

=====================================================================

Step 4, there I explain my situation.
I put the SDK on my desktop. So when I link the folder. I do like this:

C:\Users\Ethan\Desktop\Android\android-sdk_r08-windows\android-sdk-windows\tool
s> emulator.exe -avd Android -partition-size 100

There, if you didn’t put the SDK on desktop, you could use “cd” to change the folder to your tools existing folder. Such as:
C:\user\Administors\ cd d:\Documents\
It will change to your Documents folder.

And then, you just type: emulator.exe -avd Android -partition-size 100
There, you should note is: command “Android”, is my AVD NAME at Step 2, I created.
Then press “Enter”, open the emulator.

=====================================================================

Step 5, cuz I update the SDK to the Android 2.3 .
So, something changed. The “adb” file is not in the “tools” folder, but in “platform-tools” folder. So you still need to change the Adress to this.

For me is :

cmd

C:\Users\Ethan\ cd C:\Users\Ethan\Desktop\Android\android-sdk_r08-windows\android-sdk-windows\platform-tools

Then it should like this:
C:\Users\Ethan\Desktop\Android\android-sdk_r08-windows\android-sdk-windows\platform-tools\ adb pull /system/build.prop [Press “Enter”]

Next, go to “platform-tools” find out “build.prop” file, use TXT edit it.

=====================================================================

Step 6, When you open the “build.prop” file, then you should add ” ro.config.nocheckin=1 ” this after the whole text. And save, quit.

For the push it back, there are 2 commands: (below the folder of “platform-tools” )
adb remount
adb push build.prop /system/

After push build.prop back, we should download the Android Market files to install on our AVM.

These are: GoogleServicesFramework.apk and Vending.apk
Here is the downloading webpage, you can enter and download.

Download android market apk files

After you download and uncompress the files, put them to “platform-tools” folder.
Next, Also need to use cmd.
(under “platform-tools” folder)
adb push GoogleServicesFramework.apk /system/app
adb push Vending.apk /system/app
adb shell rm /system/app/SdkSetup.apk
(PS: there you can type this command again to ensure SdkSetup.apk has been deleted.)
adb shell rm /system/app/SdkSetup.apk

At last, you should go to user file, eg: C:\user\Administors\
for me is C:\Users\Ethan\. Find out your avd folder,
and delete

image: userdata-qemu.img,
userdata.img,
cache.img

Finish the whole thing. Now you can close your AVM, and use the normal way to start your AVM (SDK Manager).
After loading, you will have Android Market on your panel.

[ Android ] DAY-2 Android Testing

Posted: January 3, 2011 in Android

Today, I followed Google Tutorial, finished my first Android program.

Although this one is so easy. But “Good begining than nothing”, hope later I can create more useful and good applications.

Thanks.

There, I put the downloading link, for you to try and debug this application.