Suppose the url of the php webservice is as follow :
http://XX.XX.XXX.XX/~serverji/home_expanditure/gethistory.php?uid=4&month=10&year=2012
XX.XX.XXX.XX stands for the server IP.
And the response from the this url is like this :
{"date":["2012-10-13","2012-10-11","2012-10-08"],"category":["The Food Expense","rent","Communication costs"],"description":["nasto","google","fii"],"expenditure":["40","100","123"]}
Then we have to go for this kind of requesting to the url :
public class HistoryDto {
String date;
String category;
String descri;
float expe;
}
static String url = "http://XX.XX.XX.XXX/~serverji/home_expanditure/";
public static ArrayList<HistoryDto> gethistory(int month, String year) {
String result = "";
InputStream is = null;
ArrayList<HistoryDto> hisList = new ArrayList<HistoryDto>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("uid", Myapplication
.getuserID()));
nameValuePairs.add(new BasicNameValuePair("month", "" + month));
nameValuePairs.add(new BasicNameValuePair("year", year));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url + "gethistory.php?");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString().trim();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
JSONArray JArray_date = jObj.getJSONArray("date");
JSONArray JArray_cat = jObj.getJSONArray("category");
JSONArray JArray_dis = jObj.getJSONArray("description");
JSONArray JArray_exp = jObj.getJSONArray("expenditure");
for (int i = 0; i < JArray_date.length(); i++) {
HistoryDto dto = new HistoryDto();
dto.date = JArray_date.getString(i);
dto.category = JArray_cat.getString(i);
dto.descri = JArray_dis.getString(i);
dto.expe = (float) JArray_exp.getDouble(i);
hisList.add(dto);
}
} catch (JSONException e) {
e.printStackTrace();
}
return hisList;
}
This is how we got the result to the ArrayList and populate in the android Activities.
Search This Blog
Sunday, December 30, 2012
Calling the PHP web service in android and fetch the result in Android
Make the thread to display timer for the Games using the method to Display Time in HH:MM:SS format
Firstly make one static variable for the counter for the timer which increase the every sec.
static int con = 0;
Now make one thread in which it sleeps every one sec and display it in runOnUiThread. This thread used to Display the counter in HH:MM:SS format using the simply one formatTime method.
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
counter.setText(formatTime(Long.parseLong("" + con)));
con++;
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
The formatTime method to display the counter in HH:MM:SS format is below.
private String formatTime(long millis) {
String output = "00:00:00";
long seconds = millis;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;
String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);
if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;
output = hoursD + " : " + minutesD;
return output;
}
This is how we can put the Timer in Game or any part of coding where the difference between the time is needed at that time also we can set the kind of methods.
static int con = 0;
Now make one thread in which it sleeps every one sec and display it in runOnUiThread. This thread used to Display the counter in HH:MM:SS format using the simply one formatTime method.
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
runOnUiThread(new Runnable() {
@Override
public void run() {
counter.setText(formatTime(Long.parseLong("" + con)));
con++;
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
The formatTime method to display the counter in HH:MM:SS format is below.
private String formatTime(long millis) {
String output = "00:00:00";
long seconds = millis;
long minutes = seconds / 60;
long hours = minutes / 60;
seconds = seconds % 60;
minutes = minutes % 60;
hours = hours % 60;
String minutesD = String.valueOf(minutes);
String hoursD = String.valueOf(hours);
if (minutes < 10)
minutesD = "0" + minutes;
if (hours < 10)
hoursD = "0" + hours;
output = hoursD + " : " + minutesD;
return output;
}
This is how we can put the Timer in Game or any part of coding where the difference between the time is needed at that time also we can set the kind of methods.
Labels:
runOnUiThread,
Thread,
Time
Thursday, December 27, 2012
Getting contact list from the phone
just copy the below code in your android code and see the LOGCAT.
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
public class GetContactsDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readContacts();
}
public void readContacts(){
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
System.out.println("name : " + name + ", ID : " + id);
// get the <span id="IL_AD10" class="IL_AD">phone number</span>
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String phone = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("phone" + phone);
}
pCur.close();
// get email and type
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
System.out.println("Email " + email + " Email Type : " + emailType);
}
emailCur.close();
// Get note.......
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
System.out.println("Note " + note);
}
noteCur.close();
//Get Postal Address....
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
// Do something with these....
}
addrCur.close();
// Get Instant Messenger.........
String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
}
imCur.close();
// Get Organizations.........
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
orgCur.close();
}
}
}
}
}
You can get the all contacts in your Logcat. Just give the permission to the menifest for reading the contact.
Labels:
ContactsContract,
cursor,
query
Wednesday, December 26, 2012
Keep screen on when the Activity running using power manager
First of all make the object of the Power manage.
protected PowerManager.WakeLock mWakeLock;
Now in onCreate method use the following to make the screen ON in the particular activity.
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Tag");
this.mWakeLock.acquire();
Labels:
POWER_SERVICE,
PowerManager
Wednesday, December 12, 2012
Finding the index of the Array from the given value
Let's say there is a number of values in array like the following.
Arrays.asList(array).indexOf(4);
This will returns the index of the value in array.
Thursday, October 4, 2012
passing the Double values to the String
result = number1/number2
String stringdouble= Double.toString(result);
textview1.setText(stringdouble));
or you can use the nuberformate also.
Double result = number1/number2;
NumberFormat nm = NumberFormat.getNumberInstance();
textview1.setText(nm.format(result));
For 3 decimal digit
private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.###");
textview1.setText(REAL_FORMATTER.format(result));
String stringdouble= Double.toString(result);
textview1.setText(stringdouble));
or you can use the nuberformate also.
Double result = number1/number2;
NumberFormat nm = NumberFormat.getNumberInstance();
textview1.setText(nm.format(result));
For 3 decimal digit
private static DecimalFormat REAL_FORMATTER = new DecimalFormat("0.###");
textview1.setText(REAL_FORMATTER.format(result));
Labels:
DecimalFormat,
NumberFormat
Wednesday, June 20, 2012
DOM parsing using xml
Put the following code in the xml file.
<Name>Cryptography</Name>
<Author>Harish</Author>
<Price>$200</Price>
</Book>
<Book>
<Name>Android</Name>
<Author>Harish</Author>
<Price>$250</Price>
</Book>
</Books>
Method to parse this as the xml file and read in the method.
public HashMap doDomParsing(String strUrl, String strParent, String[] child)
{
HashMap hmap, hmapchild = null;
URL url;
hmap = new HashMap();
try
{
//url = new URL(strUrl);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
NodeList properties = node.getChildNodes();
hmapchild = new HashMap();
for(int j=0 ; j < properties.getLength() ; j++)
{
Node property = properties.item(j);
String nodename = property.getNodeName();
Log.e("Node NAME", nodename);
for(int inew =0 ;inew < child.length ; inew++)
{
if(nodename.equalsIgnoreCase(child[inew]))
{
hmapchild.put(nodename, property.getFirstChild().getNodeValue());
}
}
}
hmap.put(i, hmapchild);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return hmap;
}
<Books>
<Book><Name>Cryptography</Name>
<Author>Harish</Author>
<Price>$200</Price>
</Book>
<Book>
<Name>Android</Name>
<Author>Harish</Author>
<Price>$250</Price>
</Book>
</Books>
Method to parse this as the xml file and read in the method.
public HashMap doDomParsing(String strUrl, String strParent, String[] child)
{
HashMap hmap, hmapchild = null;
URL url;
hmap = new HashMap();
try
{
//url = new URL(strUrl);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(getClass().getResourceAsStream("/res/raw/parse.xml")));
NodeList nodeList = doc.getElementsByTagName("item");
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
NodeList properties = node.getChildNodes();
hmapchild = new HashMap();
for(int j=0 ; j < properties.getLength() ; j++)
{
Node property = properties.item(j);
String nodename = property.getNodeName();
Log.e("Node NAME", nodename);
for(int inew =0 ;inew < child.length ; inew++)
{
if(nodename.equalsIgnoreCase(child[inew]))
{
hmapchild.put(nodename, property.getFirstChild().getNodeValue());
}
}
}
hmap.put(i, hmapchild);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return hmap;
}
Labels:
Domparsing,
Hashmap
Thursday, June 7, 2012
How to get the battery level And the phone number of the phone
For the bettery level of the phone we need to write the following code.
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra("level", -1);
int scale = intent.getIntExtra("scale", -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100) / scale;
}
batterLevel.setText("Battery Level Remaining: " + level + "%");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
}
Here level indicates the bettery level of the phone.
For getting the phone number of the phone we have to insert the following code...
TelephonyManager phoneManager = (TelephonyManager) getApplicationContext()
.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = phoneManager.getLine1Number();
Here phoneNumber indicates the number of the current phone.
Labels:
battery,
broadcastreceiver,
Intent
Tuesday, March 27, 2012
Display a Random Number in android on button click
To generate random number in Android, class java.util.Random can be used.
This class java.util.Random provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.
It support two public constructor:
Random() - Construct a random generator with the current time of day in milliseconds as the initial state.
Random(long seed) - Construct a random generator with the given seed as the initial state.
<?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="@string/hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Generate Random number"
android:id="@+id/generate"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/generatenumber"
/>
</LinearLayout>
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class RandomNumber extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Random myRandom = new Random();
Button buttonGenerate = (Button)findViewById(R.id.generate);
final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);
buttonGenerate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(myRandom.nextInt()));
}
This class java.util.Random provides methods that generates pseudo-random numbers of different types, such as int, long, double, and float.
It support two public constructor:
Random() - Construct a random generator with the current time of day in milliseconds as the initial state.
Random(long seed) - Construct a random generator with the given seed as the initial state.
Put the following code in the main.xml.
<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="@string/hello"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Generate Random number"
android:id="@+id/generate"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/generatenumber"
/>
</LinearLayout>
RandomNumber.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class RandomNumber extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Random myRandom = new Random();
Button buttonGenerate = (Button)findViewById(R.id.generate);
final TextView textGenerateNumber = (TextView)findViewById(R.id.generatenumber);
buttonGenerate.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
textGenerateNumber.setText(String.valueOf(myRandom.nextInt()));
}
});
}
}
}
}
Monday, March 26, 2012
Android Text to Speech
TextToSpeech is the great feature of Android. Text to Speech (TTS) which speaks the text in different languages usually selected by the user or you can also put the default user language for the TTS.
First of all make the xml file with the one EditText and Button. And make the following code working in your java file for the TTS. You need to implement the Interface of the TTS TextToSpeech.OnInitListener.
First of all make the xml file with the one EditText and Button. And make the following code working in your java file for the TTS. You need to implement the Interface of the TTS TextToSpeech.OnInitListener.
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AndroidTextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
txtText = (EditText) findViewById(R.id.txtText);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
TTS();
}
});
}
@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
else
{
btnSpeak.setEnabled(true);
TTS();
}
}
btnSpeak.setEnabled(true);
TTS();
}
}
else
{
Log.e("TTS", "Initilization Failed!");
}
}
private void TTS() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You can change the language by the oneline code
Log.e("TTS", "Initilization Failed!");
}
}
private void TTS() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
You can change the language by the oneline code
tts.setLanguage(Locale.GERMANY);
tts.setSpeechRate(1.5);
Labels:
EditText,
TextToSpeech,
TextView
Thursday, March 8, 2012
Creating the Options Menu and Itemselected methods in android
You can use the following code inside the menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu1"
android:alphabeticShortcut="s"
android:title="menu1 title"
/>
<item
android:id="@+id/menu2"
android:alphabeticShortcut="t"
android:title="menu2 title"
/>
</menu>
now the two methods for the invoking the menu and function which is to be called on the item selected.
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/menu1"
android:alphabeticShortcut="s"
android:title="menu1 title"
/>
<item
android:id="@+id/menu2"
android:alphabeticShortcut="t"
android:title="menu2 title"
/>
</menu>
now the two methods for the invoking the menu and function which is to be called on the item selected.
@override
public boolean onCreateOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
//menu.add(R.menu.main_menu);
//menu.add(Menu.NONE, 101,Menu.FIRST,this.getResources().getString(R.string.Title));
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.main_menu, menu);
return true;
}
you can use the both the method of invoking the menu. First one by the menu.add and second one by the inflating the menu.xml file Now on the itemselectedlistner is used by the following code.
public boolean onCreateOptionsMenu (Menu menu){
super.onCreateOptionsMenu(menu);
//menu.add(R.menu.main_menu);
//menu.add(Menu.NONE, 101,Menu.FIRST,this.getResources().getString(R.string.Title));
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.main_menu, menu);
return true;
}
you can use the both the method of invoking the menu. First one by the menu.add and second one by the inflating the menu.xml file Now on the itemselectedlistner is used by the following code.
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu1:
// your code here
case R.id.menu2:
// your code here
}
return false;
}
just pass the id in switch-case and do whatever you want by selecting the those menu.
switch(item.getItemId()){
case R.id.menu1:
// your code here
case R.id.menu2:
// your code here
}
return false;
}
just pass the id in switch-case and do whatever you want by selecting the those menu.
Labels:
menu,
MenuInflater
Maintaining the state of the User in Android application throughout
you can use the Application class in you activity. By extending the Application class you can maintain the stat in android throughout the application. It means you can call those variables in the application in all the activity.
public class SampleApplication extends Application {
private static String username;
private static String password;
@Override
public void onCreate() {
super.onCreate();
username="";
password="";
}
public static String getUsername() {
return username;
}
public static void setUsername(String username) {
SampleApplication.username = username;
}
public static String getPassword() {
return password;
}
public static void setPassword(String password) {
SampleApplication.password = password;
}
}
By using this code you can set and get the username and password in any activity. And maintain the state of your username and password. Just you need to add the class name in the manifest.xml like this way.
<application
android:name=".SampleApplication"
android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".SampleApp"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
SampleApplication.setUsername("");
String currentUserName=SampleApplication.getUsername();
SampleApplication.setPassword("");
String currentPassword=SampleApplication.getPassword();
By this you can maintain the stat of the user in all over the application.
Labels:
Application
Checking the network Availability
You can check the network is available or not in your android device.
OR
package com.network.availibility;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;
public class NetworkAvailibilityActivity extends Activity {
/** Called when the activity is first created. */
private boolean isconnected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tx = (TextView)findViewById(R.id.ischeking);
isconnected = isConnected(NetworkAvailibilityActivity.this);
if(isconnected == true){
tx.setText("You are connected to the internet");
}
else{
tx.setText("Please connect your phone to internet");
}
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork =
cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileNetwork =
cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (wifiNetwork.isAvailable()) {
return wifiNetwork.isConnectedOrConnecting();
}
else if (mobileNetwork.isAvailable()) {
return mobileNetwork.isConnectedOrConnecting();
}
else if(activeNetwork.isAvailable()) {
return activeNetwork.isConnectedOrConnecting();
}
else{
return false;
}
}
}
public boolean isNetworkAvailable()
{
ConnectivityManager cm=
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check if we are connected
if (networkInfo != null && networkInfo.isConnected())
{
return true;
}
return false;
}
}
OR
package com.network.availibility;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.TextView;
public class NetworkAvailibilityActivity extends Activity {
/** Called when the activity is first created. */
private boolean isconnected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tx = (TextView)findViewById(R.id.ischeking);
isconnected = isConnected(NetworkAvailibilityActivity.this);
if(isconnected == true){
tx.setText("You are connected to the internet");
}
else{
tx.setText("Please connect your phone to internet");
}
}
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork =
cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobileNetwork =
cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (wifiNetwork.isAvailable()) {
return wifiNetwork.isConnectedOrConnecting();
}
else if (mobileNetwork.isAvailable()) {
return mobileNetwork.isConnectedOrConnecting();
}
else if(activeNetwork.isAvailable()) {
return activeNetwork.isConnectedOrConnecting();
}
else{
return false;
}
}
}
You just need to give the permission of the INTERNET and ACCESS_NETWORK_STATE.
Labels:
ConnectivityManager,
Internet,
NetworkInfo
Run the ProgresBar using the Handler
First of all create tha main.xml file and insert the following code into it.
<?xml version="1.0" encoding="utf-8"?>
public class ProgressBar extends Activity {
Run your application. Once you press your button the ProgressBar will get updated from the background thread.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ProgressBar android:id="@+id/progressBar1" style="?
android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="4dip" >
</ProgressBar>
<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startProgress"
android:text="Start Progress" >
</Button>
</LinearLayout>
Now make an java file and insert the following code into it.
private Handler handler;
private ProgressBar progress;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
progress = (ProgressBar) findViewById(R.id.progressBar1);
handler = new Handler();
}
public void startProgress(View view) {
// Do something long
Runnable runnable = new Runnable() {
@Override public void run()
{
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(2000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
@Override public void run() {
progress.setProgress(value);
}
});
}
}
};
new Thread(runnable).start();
}
}
Labels:
Buttons,
Handler,
Progressbar,
Thread
Subscribe to:
Posts (Atom)