Search This Blog

Monday, January 7, 2013

LISTVIEW gets refresh and change the value while scroling issue(SOLVED)



First of all main.xml file will be like below:


<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" >
    <ListView
        android:id="@+id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
         />
</RelativeLayout>

Row file for the inflator is as below.



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:max="100"/>
    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="click to see row number" />
        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0" />
    </LinearLayout>
</LinearLayout>




Now the class in the activity should be like this.... See the getview method for the logic of not refreshing the list view after scrolling :


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ListView lv = (ListView) findViewById(R.id.list);
lv.setAdapter(new ListAdapter(MainActivity.this));
}

private class ListAdapter extends BaseAdapter {
private Context con;
private int size = 20;
private int s[] = new int[20];

public ListAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.con = mainActivity;
for (int i = 0; i < size; i++) {
s[i] = 0;
}

}

@Override
public int getCount() {
// TODO Auto-generated method stub
return size;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View convertView,ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = LayoutInflater.from(this.con);
View View = inflater.inflate(R.layout.list_row, null);
SeekBar seekbar = (SeekBar) View.findViewById(R.id.seekBar1);
Button btnrow = (Button) View.findViewById(R.id.button1);
final Button btnseek = (Button) View.findViewById(R.id.button2);

seekbar.setProgress(s[position]);
btnseek.setText("" + s[position]);

seekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
btnseek.setText("" + progress);
s[position] = progress;

}
});

return View;
}

}

Wednesday, January 2, 2013

Get all the application installed on your system



First of all add the xml for the list of the application installed on your devices.

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

    <ListView
        android1:id="@+id/listView1"
        android1:layout_width="match_parent"
        android1:layout_height="wrap_content"
        android1:layout_alignParentLeft="true"
        android1:layout_alignParentTop="true" >
    </ListView>

</RelativeLayout>

Here is the code for the row of the list.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="17dp"
        android:layout_marginTop="22dp"
       />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/imageView1"
        android:layout_marginLeft="36dp"
        android:layout_toRightOf="@+id/imageView1"
        android:text="TextView" />

</RelativeLayout>


Now after that add the following code in your main activity.


public class MainActivity extends Activity {

ArrayList<PInfo> arrylist;

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

arrylist = getPackages();

for (int i = 0; i < arrylist.size(); i++) {
Log.i("log_tag", "=======" + arrylist.get(i).icon);
}

ListView l = (ListView) findViewById(R.id.listView1);

l.setAdapter(new ListAdatp(this, arrylist));

}

class PInfo {
private String appname = "";
private String pname = "";
private String versionName = "";
private int versionCode = 0;
private String move2sd;
private Drawable icon;

private void prettyPrint() {
Log.v(appname + "\t" + pname + "\t" + versionName + "\t"
+ versionCode, "");
}

}

private ArrayList<PInfo> getPackages() {
ArrayList<PInfo> apps = getInstalledApps(false); /*
* false = no system
* packages
*/

final int max = apps.size();
for (int i = 0; i < max; i++) {
apps.get(i).prettyPrint();

}
return apps;

}

private ArrayList<PInfo> getInstalledApps(boolean getSysPackages) {
ArrayList<PInfo> res = new ArrayList<PInfo>();
List<PackageInfo> packs = getPackageManager().getInstalledPackages(0);
for (int i = 0; i < packs.size(); i++) {
PackageInfo p = packs.get(i);
if ((!getSysPackages) && (p.versionName == null)) {
continue;
}
PInfo newInfo = new PInfo();
newInfo.appname = p.applicationInfo.loadLabel(getPackageManager())
.toString();
newInfo.pname = p.packageName;
newInfo.versionName = p.versionName;
newInfo.versionCode = p.versionCode;
newInfo.icon = p.applicationInfo.loadIcon(getPackageManager());

res.add(newInfo);
}
return res;
}

public class ListAdatp extends BaseAdapter {

Activity ativity;
ArrayList<PInfo> adptarrlist;

public ListAdatp(MainActivity mainActivity, ArrayList<PInfo> arrylist) {

// TODO Auto-generated constructor stub
ativity = mainActivity;
adptarrlist = arrylist;

}

@Override
public int getCount() {
// TODO Auto-generated method stub
return adptarrlist.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub

LayoutInflater inflt = (LayoutInflater) ativity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

convertView = inflt.inflate(R.layout.listrow, null);

ImageView img = (ImageView) convertView
.findViewById(R.id.imageView1);
TextView txt = (TextView) convertView.findViewById(R.id.textView1);
img.setBackgroundDrawable(adptarrlist.get(position).icon);
txt.setText("(" + adptarrlist.get(position).appname + ")  "
+ adptarrlist.get(position).pname);

txt.setOnClickListener(new OnClickListener() {

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

Intent LaunchIntent = getPackageManager()
.getLaunchIntentForPackage(
adptarrlist.get(position).pname);
startActivity(LaunchIntent);
}
});

return convertView;
}

}

}

Sunday, December 30, 2012

Calling the PHP web service in android and fetch the result in Android

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.

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.

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.

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();

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.

int[] array = {1,2,3,4,5,6};

Arrays.asList(array).indexOf(4);

This will returns the index of the value in array.