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










5 comments:

  1. Hi I have sent you a code please have a look on that. have fun

    ReplyDelete
  2. hi, the code which u send me is bit confusing.what i need to do is,i've to pick some jokes from my database on the basis of various jokes category.but first i've to display joke category in gridview.for now i dont want to display image in gridview but only text through json.if u need code then i'll send u.can u send something like this

    ReplyDelete
  3. My Main.java code is here

    package com.cbsejokes.android;

    import java.util.ArrayList;
    import java.util.HashMap;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import com.pxr.tutorial.xmltest.R;
    import android.app.ListActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.GridView;
    import android.widget.ListAdapter;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    public class Main extends ListActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);

    ArrayList> mylist = new ArrayList>();


    JSONObject json = JSONfunctions.getJSONfromURL("http://192.168.1.4/waqut/app/?func=getjokescategories");
    // for now i am using local url
    try{

    JSONArray jokes = json.getJSONArray("jokes");

    for(int i=0;i map = new HashMap();
    JSONObject e = jokes.getJSONObject(i);

    //category_id is the id of jokes category and category_name is the type of joke category map.put("category_id", String.valueOf(e.getString("category_id")));
    map.put("jokes", e.getString("category_name"));

    mylist.add(map);
    }
    }catch(JSONException e) {
    Log.e("log_tag", "Error parsing data "+e.toString());
    }

    GridView gridView=(GridView) findViewById(R.id.grid);

    ListAdapter Adapter = new SimpleAdapter(this, mylist , R.layout.main,
    new String[] { "jokes"},
    new int[] { R.id.item});

    setListAdapter(Adapter);
    // gridView.setAdapter(Adapter);
    /* final ListView lv = getListView();

    lv.setTextFilterEnabled(true);

    lv.setOnItemClickListener(new OnItemClickListener() {


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
    //HashMap o = (HashMap) lv.getItemAtPosition(position);

    Toast.makeText(Main.this, "ID '" + lv.getItemAtPosition(position) + "' was clicked.", Toast.LENGTH_SHORT).show();

    //lv.getItemAtPosition(position);
    }

    }); */

    }
    }



    ReplyDelete
  4. JSONfunction.java code is here

    package com.cbsejokes.android;

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.util.Log;

    public class JSONfunctions {

    public static JSONObject getJSONfromURL(String url){
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    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();
    }catch(Exception e){
    Log.e("log_tag", "Error converting result "+e.toString());
    }

    try{

    jArray = new JSONObject(result);
    }catch(JSONException e){
    Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
    }
    }


    main.xml is here







    listplaceholder.xml is here










    i have send u the snapshot of what i want and what i m getting.please have a look on that.hope u'll give some solution

    ReplyDelete
  5. could u send me this back by saturday or sunday?image will be static and text will be dynamic.i've done all this in listview but unable to do in gridview.i've to complete it by monday.

    ReplyDelete