Search This Blog

Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Sunday, March 3, 2013

Calling the web-service in android with POST and GET method

Hello guys Here i am posting the method of calling the webservice in android using POST and GET method.


public class RestClient {

   private ArrayList <NameValuePair> params;
   private ArrayList <NameValuePair> headers;

   private String url;

   private int responseCode;
   private String message;

   private String response;

   public String getResponse() {
       return response;
   }

   public String getErrorMessage() {
       return message;
   }

   public int getResponseCode() {
       return responseCode;
   }

   public RestClient(String url)
   {
       this.url = url;
       params = new ArrayList<NameValuePair>();
       headers = new ArrayList<NameValuePair>();
   }

   public void AddParam(String name, String value)
   {
       params.add(new BasicNameValuePair(name, value));
   }

   public void AddHeader(String name, String value)
   {
       headers.add(new BasicNameValuePair(name, value));
   }

   public void Execute(RequestMethod method) throws Exception
   {
       switch(method) {
           case GET:
           {
               //add parameters
               String combinedParams = "";
               if(!params.isEmpty()){
                   combinedParams += "?";
                   for(NameValuePair p : params)
                   {
                       String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),”UTF-8″);
                       if(combinedParams.length() > 1)
                       {
                           combinedParams  +=  "&" + paramString;
                       }
                       else
                       {
                           combinedParams += paramString;
                       }
                   }
               }

               HttpGet request = new HttpGet(url + combinedParams);

               //add headers
               for(NameValuePair h : headers)
               {
                   request.addHeader(h.getName(), h.getValue());
               }

               executeRequest(request, url);
               break;
           }
           case POST:
           {
               HttpPost request = new HttpPost(url);

               //add headers
               for(NameValuePair h : headers)
               {
                   request.addHeader(h.getName(), h.getValue());
               }

               if(!params.isEmpty()){
                   request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
               }

               executeRequest(request, url);
               break;
           }
       }
   }

   private void executeRequest(HttpUriRequest request, String url)
   {
       HttpClient client = new DefaultHttpClient();

       HttpResponse httpResponse;

       try {
           httpResponse = client.execute(request);
           responseCode = httpResponse.getStatusLine().getStatusCode();
           message = httpResponse.getStatusLine().getReasonPhrase();

           HttpEntity entity = httpResponse.getEntity();

           if (entity != null) {

               InputStream instream = entity.getContent();
               response = convertStreamToString(instream);

               // Closing the input stream will trigger connection release
               instream.close();
           }

       } catch (ClientProtocolException e)  {
           client.getConnectionManager().shutdown();
           e.printStackTrace();
       } catch (IOException e) {
           client.getConnectionManager().shutdown();
           e.printStackTrace();
       }
   }

   private static String convertStreamToString(InputStream is) {

       BufferedReader reader = new BufferedReader(new InputStreamReader(is));
       StringBuilder sb = new StringBuilder();

       String line = null;
       try {
           while ((line = reader.readLine()) != null) {
               sb.append(line + "\n");
           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           try {
               is.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }
}

Now here is the calling example of the method.

RestClient client = new RestClient(URL of the webservice); 
client.AddParam("param1", "String of param1"); 
client.AddParam("param2", "String of param2"); 
client.AddParam("Email", email); 
client.AddParam("Passwd", passcode); 
          try { 
                   client.Execute(RequestMethod.POST);  //  OR GET 
              }   
            catch (Exception e) {  
                  e.printStackTrace(); 
            }
 String response = client.getResponse();

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.

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.

Thursday, December 1, 2011

ADD ELEMENT IN THE LIST AND REMOVE IT BY CLICKING IT

First of all make an XML file called listadapter.xml file and insert the following

<?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">
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="230dp" 
android:layout_height="wrap_content" 
android:id="@+id/myEditText"/>
<Button android:text="Add"
android:id = "@+id/Add"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background = "@drawable/button_shape"
/>
</LinearLayout>
<ListView
android:layout_height="wrap_content" 
android:layout_width="wrap_content" 
android:id="@+id/MyListView">
</ListView>
</LinearLayout>



AND create the class file called ListAdapter.java and insert the following into it



import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import android.widget.Toast;


public class ListAdapter extends Activity {
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       Toast.makeText(ListAdapter.this, "Redirecting to List Activity", 400000).show();
     //  TextView textview = new TextView(this);
     //  textview.setText("This is the Artists tab");
       setContentView(R.layout.listadapter);
       Button bt = (Button)findViewById(R.id.Add); 
       ListView lv = (ListView)findViewById(R.id.MyListView);
       final EditText myEditText= (EditText)findViewById (R.id.myEditText);
       final ArrayList<String> videolinks = new ArrayList<String>();
       final ArrayAdapter<String> aa;
       
       aa= new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,videolinks);
       
       lv.setAdapter(aa);
       
       bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(myEditText.getText().length() != 0)
{
videolinks.add(0, myEditText.getText().toString().trim());
aa.notifyDataSetChanged();
myEditText.setText("");
}
}
       });
       lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// TODO Auto-generated method stub
AlertDialog.Builder ad  = new AlertDialog.Builder(ListAdapter.this);
ad.setTitle("Delete?");
ad.setMessage("Are you sure you want to delete " + arg2);
final int positionToRemove = arg2;
ad.setNegativeButton("Cancel", null);
ad.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) 
{
               videolinks.remove(positionToRemove);
               aa.notifyDataSetChanged();
       }
});
ad.show();
}
});
  }
}