Category Archives: Android

「Android」response.getStatusLine().getStatusCode()の使い方

サンプルコード
public static InputStream get(String url)throws IOException ,Exception {

urlStr = url;
isConnecting = true;

HttpGet httpGet = new HttpGet(urlStr);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,
connectionTimeout);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
return inputStream;}
else return null;

}
}

「Android入門」WebViewを利用するサンプルコード

1.activity_main.xml
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent” >

<WebView
android:id=”@+id/webView1″
android:layout_width=”match_parent”
android:layout_height=”match_parent”
/>
</LinearLayout>

2、MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends Activity {

private WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {

view.loadUrl(url);
return true;
}
});
webView.loadUrl(“http://www.example.com”);
}

@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;
}

}

 

3.AndroidManifest.xml
追記
<uses-permission android:name=”android.permission.INTERNET”/>

「Android」ActionBarActivityのFullScreenを設定するめも

サンプルコード

<style name=”ActionBarFullScreen” parent=”Theme.AppCompat.Light.NoActionBar”>
<item name=”android:windowFullscreen”>true</item>
<item name=”android:windowNoTitle”>true</item>
<item name=”android:windowContentOverlay”>@null</item>
</style>

「Android」SQLiteデータベースを使用するトランザクションのサンプルコード

db.beginTransaction();  //トランザクション開始
try{
//パッチ処理
for(Collection c:colls){

insert(db, c);
}

db.setTransactionSuccessful(); //トランザクション実行成功
}catch(Exception e){

MyLog.printStackTraceString(e);

}finally{

db.endTransaction(); //トランザクション完了

}

「Android入門」Activity通信のサンプルコード

サンプルコード

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnOpen=(Button)this.findViewById(R.id.btnOpen);
btnOpen.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {

Intent intent=new Intent(MainActivity.this, OtherActivity.class);
Bundle bundle=new Bundle();
bundle.putString(“name”, “yamada”);
bundle.putInt(“age”, 26);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
}

「Android」複数のSQL構文は一つのトランザクションに実行するコード

Javaコード
//トランザクションテスト
public void payment()
{
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
//トランザクション開始
db.beginTransaction();
try
{
db.execSQL(“update employee set amount=amount-10 where employeeid=?”, new Object[]{1});
db.execSQL(“update employee set amount=amount+10 where employeeid=?”, new Object[]{2});
//トランザクション成功
db.setTransactionSuccessful();
}
catch(Exception e){
throw(e);
}
finally
{
//トランザクション終了
db.endTransaction();
}
}

「Andorid」SQLiteデータベースを作成、画像を保存するコード

//DB作成
public class DBService extends SQLiteOpenHelper {

private final static int VERSION = 1;
private final static String DATABASE_NAME = “uniteqinfocher.db”;

public DBService(Context context) {
this(context, DATABASE_NAME, null, VERSION);
}

public DBService(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
String sql = “CREATE TABLE [infocher](”
+ “[_id] INTEGER PRIMARY KEY AUTOINCREMENT,”
+ “[photo] BINARY)”; //binaryフォーマット保存

db.execSQL(sql);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
db.execSQL(“DROP TABLE IF EXISTS[infocher]”);
} else {
return;
}
onCreate(db);
}
}

//DBに画像を保存
public void savePhoto(Drawable appIcon, Context mContext){
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.app_view, null);
ImageView iv = (ImageView) v.findViewById(R.id.appicon);
iv.setImageDrawable(appIcon);
String INSERT_SQL = “INSERT INTO infocher(photo) values(?)”;
SQLiteDatabase db = mDBService.getWritableDatabase(); // DB取得
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
((BitmapDrawable) iv.getDrawable()).getBitmap().compress(
CompressFormat.PNG, 100, baos);//圧縮拡張
Object[] args = new Object[] {baos.toByteArray() };
db.execSQL(INSERT_SQL, args);
baos.close();
db.close();
} catch (Exception e) {
e.printStackTrace();
}

}

//DBから画像取得
public void getPhoto() {
String SELECT_SQL = “SELECT photo FROM infocher”;
ImageView appIcon = (ImageView) v.findViewById(R.id.appicon);
byte[] photo = null;
mDBService = new DBService(getContext());
SQLiteDatabase db = mDBService.getReadableDatabase();
Cursor mCursor = db.rawQuery(SELECT_SQL, null);
if (mCursor != null) {
if (mCursor.moveToFirst()) {//just need to query one time
photo = mCursor.getBlob(mCursor.getColumnIndex(“photo”));//画像取得
}
}
if (mCursor != null) {
mCursor.close();
}
db.close();
ByteArrayInputStream bais = null;
if (photo != null) {
bais = new ByteArrayInputStream(photo);
appIcon.setImageDrawable(Drawable.createFromStream(bais, “photo”));//ImageViewオブジェクトに画像を設定
}

}

「Android」ListView と ArrayAdapter の使い方

1.activity_main.xml
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >

<ListView
android:id=”@+id/list_view1″
android:layout_width=”match_parent”
android:layout_height=”match_parent”
>
</ListView>
</LinearLayout>

 

2.MainActivity.java
package com.changfa.demoViewLst;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

private String[] viewListData = {“名前:山田次郎”,”学歴:大学”,”会社:○○会社”,出身:大崎”,”age:32″};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

//ListView取得
ListView listView = (ListView) findViewById(R.id.list_view1);
//ArrayAdapter
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, viewListData);
//ArrayAdapterでデータを設定
listView.setAdapter(adapter);

//イベント追加
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String info = viewListData[position];
Toast.makeText(MainActivity.this, info, Toast.LENGTH_SHORT).show();
}
});
}

@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;
}

}

「Android」アクションバーactionbarを追加する方法まとめ

方法1
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.sample.homer”
android:versionCode=”1″
android:versionName=”1.0″>
<uses-sdk android:minSdkVersion=”18″/>
<application android:label=”@string/app_name” android:icon=”@drawable/ic_launcher”
android:theme=”@android:style/Theme.Holo”>
<activity android:name=”MyActivity”
android:label=”@string/app_name”>
<intent-filter>
<action android:name=”android.intent.action.MAIN”/>
<category android:name=”android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
</application>
</manifest>

方法2
import android.app.ActionBar;
import android.app.Activity;
import android.drm.DrmStore;
import android.os.Bundle;

public class DemoActivity extends Activity {
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.show();
}
}

「Android」IPowerManagerのshutdownインタフェースを実装するコード

Javaコード
try{
Class> ServiceManager = Class.forName(“android.os.ServiceManager”);
//ServiceManager的getService取得
Method getService = ServiceManager.getMethod(“getService”, java.lang.String.class);
//getServiceでRemoteService取得
Object oRemoteService = getService.invoke(null,Context.POWER_SERVICE);
//IPowerManager.Stub取得
Class> cStub = Class.forName(“android.os.IPowerManager$Stub”);
//asInterface取得
Method asInterface = cStub.getMethod(“asInterface”, android.os.IBinder.class);
//asInterfaceでIPowerManagerオブジェクト取得
Object oIPowerManager = asInterface.invoke(null, oRemoteService);
//shutdown()取得
Method shutdown = oIPowerManager.getClass().getMethod(“shutdown”,boolean.class,boolean.class);
//shutdown()実行
shutdown.invoke(oIPowerManager,false,true);
} catch (Exception e) {
Log.e(TAG, e.toString(), e);
}

2 / 2012345...1020...最後 »