Friday, April 5, 2013

Android Creating App Widget

Here i am presenting an idea of a widget on the main screen of the device. 




Creat a project and have main activity with name

1)JiteshActivity.java
package com.jitesh.uselesswidget;

import com.jitesh.uselesswidget.R;

import android.app.Activity;
import android.os.Bundle;

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

2)UselessWidgetProvider .java

package com.jitesh.uselesswidget.widgetprovider;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import com.jitesh.uselesswidget.R;
import com.jitesh.uselesswidget.settings.Preferences;

import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.RemoteViews.RemoteView;

public class UselessWidgetProvider extends AppWidgetProvider {
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet("http://search.twitter.com/search.json?q=twitter");
BasicResponseHandler handler = new BasicResponseHandler();
String response = null;
String text=null;
Date d=null;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
try{
response = client.execute(get,handler);
if(response!=null){
JSONObject object = new JSONObject(response);
JSONArray array = object.getJSONArray("results");
if(array.length()>0){
JSONObject tweet = array.getJSONObject(0);
text = tweet.getString("text");
String dateStr = tweet.getString("created_at");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",Locale.US);
d = sdf.parse(dateStr);
Log.v(getClass().getName(),"Date: "+d+" Text: "+text);
Editor e = preferences.edit();
e.putString(Preferences.PREFERENCE_TWEET, text);
e.putLong(Preferences.PREFERENCE_TIME, d.getTime());
e.commit();
}
}
}
catch(Exception e){
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("d/MM/yy HH:mm");
if(d==null && text==null){
text = preferences.getString(Preferences.PREFERENCE_TWEET, "Indisponible en ce moment!");
Long dateLong = preferences.getLong(Preferences.PREFERENCE_TIME, -1);
if(dateLong!=-1)d=new Date(dateLong);
}
if(d!=null && text!=null){
for(int i = 0; i<appWidgetIds.length;i++){
int appWidgetId = appWidgetIds[i];
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
remoteViews.setTextViewText(R.id.textViewText, text);
remoteViews.setTextViewText(R.id.textViewTime, sdf2.format(d));
appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
}
}
}
}

3)Preferences .java

package com.jitesh.uselesswidget.settings;

public class Preferences {
public static final String PREFERENCE_TWEET = "com.jitesh.uselesswidget.preference.tweet";
public static final String PREFERENCE_TIME = "com.jitesh.uselesswidget.preference.time";
}


4)main.xml

<?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"
    android:gravity="center_horizontal|center_vertical"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:layout_margin="20dp"
        style="@android:style/TextAppearance.Medium"
        />

</LinearLayout>

5) res/layout/widget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/appwidget_bg" >

<ImageView
   android:id="@+id/imageViewWidget"
   android:layout_width="68dp"
   android:layout_height="68dp"
   android:src="@drawable/reynders"
   android:layout_margin="8dp"
   />
<TextView
   android:id="@+id/textViewText"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:layout_toRightOf="@id/imageViewWidget"
   android:textColor="#FFFFFF"
   android:layout_marginTop="4dp"/>
<TextView
   android:id="@+id/textViewTime"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentRight="true"
   android:layout_alignParentBottom="true"
   android:textColor="#BBBBBB"
   android:layout_margin="4dp"
   />

</RelativeLayout>

7) res/xml/uselessappwidgetprovider.xml

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="1800000"
    android:initialLayout="@layout/widget"    
>
</appwidget-provider>

8)res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Go to main screen and please make long press  on the screen and select widget " twitter widget "</string>
    <string name="app_name">Twitter Widget</string>

</resources>

9)manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jitesh.uselesswidget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" />
    <uses-permission 
        android:name="android.permission.INTERNET"
        />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".JiteshActivity"
            android:theme="@android:style/Theme.Light">
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <receiver android:name=".widgetprovider.UselessWidgetProvider">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/uselessappwidgetprovider"/>
        </receiver>
    </application>

</manifest>


copy the resources to drawable










Monday, April 1, 2013

Android Using Weather API'S of yahoo

Please  read the doc at http://developer.yahoo.com/weather/

and have close look on the apis

http://where.yahooapis.com/geocode?q=ahmedabad=%5Byourappidhere%5D

http://weather.yahooapis.com/forecastrss?w=2502265

Make a new project and have the MainActivity with following code


package com.exercise.AndroidYahooWeatherDOM;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidYahooWeatherDOMActivity extends Activity {

TextView weather;

class MyWeather{
String description;
String city;
String region;
String country;

String windChill;
String windDirection;
String windSpeed;

String sunrise;
String sunset;

String conditiontext;
String conditiondate;

public String toString(){

return "\n- " + description + " -\n\n"
+ "city: " + city + "\n"
+ "region: " + region + "\n"
+ "country: " + country + "\n\n"

+ "Wind\n"
+ "chill: " + windChill + "\n"
+ "direction: " + windDirection + "\n"
+ "speed: " + windSpeed + "\n\n"

+ "Sunrise: " + sunrise + "\n"
+ "Sunset: " + sunset + "\n\n"

+ "Condition: " + conditiontext + "\n"
+ conditiondate +"\n";

}
}

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        weather = (TextView)findViewById(R.id.weather);
        
        
        String weatherString = QueryYahooWeather();
        Document weatherDoc = convertStringToDocument(weatherString);

        MyWeather weatherResult = parseWeather(weatherDoc);
        weather.setText(weatherResult.toString());
    }
    
    private MyWeather parseWeather(Document srcDoc){
   
    MyWeather myWeather = new MyWeather();
   
    //<description>Yahoo! Weather for New York, NY</description>
    myWeather.description = srcDoc.getElementsByTagName("description")
    .item(0)
    .getTextContent();
   
    //<yweather:location city="New York" region="NY" country="United States"/>
    Node locationNode = srcDoc.getElementsByTagName("yweather:location").item(0);
    myWeather.city = locationNode.getAttributes()
.getNamedItem("city")
.getNodeValue()
.toString();
myWeather.region = locationNode.getAttributes()
.getNamedItem("region")
.getNodeValue()
.toString();
myWeather.country = locationNode.getAttributes()
.getNamedItem("country")
.getNodeValue()
.toString();

//<yweather:wind chill="60" direction="0" speed="0"/>
Node windNode = srcDoc.getElementsByTagName("yweather:wind").item(0);
myWeather.windChill = windNode.getAttributes()
.getNamedItem("chill")
.getNodeValue()
.toString();
myWeather.windDirection = windNode.getAttributes()
.getNamedItem("direction")
.getNodeValue()
.toString();
myWeather.windSpeed = windNode.getAttributes()
.getNamedItem("speed")
.getNodeValue()
.toString();

//<yweather:astronomy sunrise="6:52 am" sunset="7:10 pm"/>
Node astronomyNode = srcDoc.getElementsByTagName("yweather:astronomy").item(0);
myWeather.sunrise = astronomyNode.getAttributes()
.getNamedItem("sunrise")
.getNodeValue()
.toString();
myWeather.sunset = astronomyNode.getAttributes()
.getNamedItem("sunset")
.getNodeValue()
.toString();

//<yweather:condition text="Fair" code="33" temp="60" date="Fri, 23 Mar 2012 8:49 pm EDT"/>
Node conditionNode = srcDoc.getElementsByTagName("yweather:condition").item(0);
myWeather.conditiontext = conditionNode.getAttributes()
.getNamedItem("text")
.getNodeValue()
.toString();
myWeather.conditiondate = conditionNode.getAttributes()
.getNamedItem("date")
.getNodeValue()
.toString();

    return myWeather;
    }
    
    private Document convertStringToDocument(String src){
    Document dest = null;
   
    DocumentBuilderFactory dbFactory =
    DocumentBuilderFactory.newInstance();
    DocumentBuilder parser;

    try {
    parser = dbFactory.newDocumentBuilder();
dest = parser.parse(new ByteArrayInputStream(src.getBytes()));
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
Toast.makeText(AndroidYahooWeatherDOMActivity.this, 
    e1.toString(), Toast.LENGTH_LONG).show();
} catch (SAXException e) {
e.printStackTrace();
Toast.makeText(AndroidYahooWeatherDOMActivity.this, 
    e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(AndroidYahooWeatherDOMActivity.this, 
    e.toString(), Toast.LENGTH_LONG).show();
}
   
    return dest;
    }
    
    private String QueryYahooWeather(){
    // use the api to get WOEID which i used directly in this demo
    //http://where.yahooapis.com/geocode?q=bangalore=%5Byourappidhere%5D
    String qResult = "";
    String queryString = "http://weather.yahooapis.com/forecastrss?w=2295420";
   
    HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(queryString);
        
        try {
        HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
       
        if (httpEntity != null){
        InputStream inputStream = httpEntity.getContent();
        Reader in = new InputStreamReader(inputStream);
        BufferedReader bufferedreader = new BufferedReader(in);
        StringBuilder stringBuilder = new StringBuilder();
       
        String stringReadLine = null;

        while ((stringReadLine = bufferedreader.readLine()) != null) {
        stringBuilder.append(stringReadLine + "\n");
        }
       
        qResult = stringBuilder.toString();
        }

} catch (ClientProtocolException e) {
e.printStackTrace();
Toast.makeText(AndroidYahooWeatherDOMActivity.this, 
    e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(AndroidYahooWeatherDOMActivity.this, 
    e.toString(), Toast.LENGTH_LONG).show();
}
   
        return qResult;
    }
}

the main.xml is as shown below


<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="hello buddy" />
    <ScrollView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:id="@+id/weather"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</LinearLayout>



Android phone call log/history programmatically

Create a project CallLogger with the main activity with following code

1)-

MainActivity.java


package com.jitesh.calllogger;

import java.util.Date;

import android.os.Bundle;
import android.provider.CallLog;
import android.app.Activity;
import android.database.Cursor;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {
private TextView call = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
call = (TextView) findViewById(R.id.call);
getCallDetails();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

private void getCallDetails() {

StringBuffer sb = new StringBuffer();
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
null, null, null);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;

case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;

case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir + " \nCall Date:--- " + callDayTime
+ " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
}
managedCursor.close();
call.setText(sb);
}

}


2) activity_main.xml

<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"
    tools:context=".MainActivity" >

    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TextView
            android:id="@+id/call"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/hello_world" />
    </ScrollView>

</RelativeLayout>

3) manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jitesh.calllogger"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jitesh.calllogger.MainActivity"
            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>