/**
* This method connects to server through HTTP request .
*/
private static String connect(String url){
// Create the httpclient
//HttpClient httpclient = new DefaultHttpClient();
DefaultHttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
Log.e("mSessionId",""+mSessionId);
//Header h="JSESSIONID";
//HttpRequest req=null;
//req.addHeader("JSESSIONID",mSessionId);
httpget.addHeader("JSESSIONID","mSessionId1"+":" +mSessionId);
httpget.getAllHeaders();
HeaderElementIterator it1 = new BasicHeaderElementIterator(
httpget.headerIterator());
System.out.println(httpget.getURI());
while (it1.hasNext()) {
HeaderElement elem = it1.nextElement();
System.out.println("session name"+elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
// Execute the request
HttpResponse response;
// return string
String returnString = null;
try {
// Open the webpage.
response = httpclient.execute(httpget);
// if(response.getStatusLine().getStatusCode() == 200){
if(true) {
// Connection was established. Get the content.
HttpEntity entity = response.getEntity();
//SetCookie c=new Cookie();
//SetCookie.setValue(mSessionId);
response.getAllHeaders();
Log.e("headers",""+response.getAllHeaders());
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator());
while (it.hasNext()) {
HeaderElement elem = it.nextElement();
System.out.println(elem.getName() + " = " + elem.getValue());
NameValuePair[] params = elem.getParameters();
for (int i = 0; i < params.length; i++) {
System.out.println(" " + params[i]);
}
}
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
// Load the requested page converted to a string into a JSONObject.
// JSONObject myAwway = new JSONObject(convertStreamToString(instream));
returnString = convertStreamToString(instream);
// Log.e(TAG,"instream : "+convertStreamToString(instream));
// Log.e(TAG,"myawway : "+ myAwway);
// Get the query value'
//String query = myAwway.getString("query");
// JSONObject menuObject =myAwway.getJSONObject("photos");
// Make array of the suggestions
// JSONArray suggestions =menuObject.getJSONArray("photo");
// Build the return string.
// returnString = "Found: " + suggestions.length() ;
// for (int i = 0; i < suggestions.length(); i++) {
// returnString += "\n\t" +(suggestions.getJSONObject(i).getString("id").toString());
// }
// returnString = "Found";
// Cose the stream.
instream.close();
}
}
else {
// code here for a response othet than 200. A response 200 means the webpage was ok
// Other codes include 404 - not found, 301 - redirect etc...
// Display the response line.
returnString = "Unable to load page - " + response.getStatusLine();
}
return returnString ;
}
catch (IOException ex) {
// thrown by line 80 - getContent();
// Connection was not established
returnString = "Connection failed; " + ex.getMessage();
}
// catch (JSONException ex){
// JSON errors
// returnString = "JSON failed; " + ex.getMessage();
// }
return returnString;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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();
}
}
Log.e(TAG,"sb string : "+ sb.toString());
return sb.toString();
}
Wednesday, November 30, 2011
Parsing json response
Let’s look at how to parse JSON objects in android
Android JSON Support
Android already contains the required JSON libraries. The Following class are used to parse the JSON Object.
JSONArray A JSONArray is an ordered sequence of values.
JSONObject A JSONObject is an unordered collection of name/value pairs.
JSONStringer JSONStringer provides a quick and convenient way of producing JSON text.
JSONTokener A JSONTokener takes a source string and extracts characters and tokens from it.
Steps to Parse JSON data
1. Create a JSON Object and Convert JSONString to JSON Object
JSONObject jObject = new JSONObject(jsonString);
2. Create a Key based JSONObject.
JSONObject menuObject = jObject.getJSONObject("menu");
3. Get the Value
Log.d("ID", menuObject.getString("id"));
Log.d("Value ", menuObject.getString("value"));
1> First we’ll need an example :
Lets look at a standard example from the json site http://json.org/example.html
2> Android already contains the required JSON libraries
Lets create a JSON Object;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
now we have to convert jString to the jObject ,
jObject = new JSONObject(jString);
Now we have to start extracting the content from jObject ,
Lets extract the menu object by creating a new menu object,
JSONObject menuObject = jObject.getJSONObject("menu"); Now lets extract its atrtibutes ,
String attributeId = menuObject.getString("id"); String attributeValue = menuObject.getString("value"); JSONObject popupObject = menuObject.getJSONObject("popup");
since “popup” is not plainly a String lets extract it to an object ,
3> Now popup contains an array of “menuitem”
So, we’ll have to extract it to a JSONArray,
JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); Since it contains 3 items lets put it in a for loop.
for (int i = 0; i < 3; i++) { System.out.println(menuitemArray.getJSONObject(i) .getString("value").toString()); System.out.println(menuitemArray.getJSONObject(i).getString( "onclick").toString()); }
Android JSON Support
Android already contains the required JSON libraries. The Following class are used to parse the JSON Object.
JSONArray A JSONArray is an ordered sequence of values.
JSONObject A JSONObject is an unordered collection of name/value pairs.
JSONStringer JSONStringer provides a quick and convenient way of producing JSON text.
JSONTokener A JSONTokener takes a source string and extracts characters and tokens from it.
Steps to Parse JSON data
1. Create a JSON Object and Convert JSONString to JSON Object
JSONObject jObject = new JSONObject(jsonString);
2. Create a Key based JSONObject.
JSONObject menuObject = jObject.getJSONObject("menu");
3. Get the Value
Log.d("ID", menuObject.getString("id"));
Log.d("Value ", menuObject.getString("value"));
1> First we’ll need an example :
Lets look at a standard example from the json site http://json.org/example.html
{"menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } }}
you could either save this in a file or save it in a string…..like I’ve done
2> Android already contains the required JSON libraries
Lets create a JSON Object;
private JSONObject jObject;and lets our example be a String ,
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
now we have to convert jString to the jObject ,
jObject = new JSONObject(jString);
Now we have to start extracting the content from jObject ,
Lets extract the menu object by creating a new menu object,
JSONObject menuObject = jObject.getJSONObject("menu"); Now lets extract its atrtibutes ,
String attributeId = menuObject.getString("id"); String attributeValue = menuObject.getString("value"); JSONObject popupObject = menuObject.getJSONObject("popup");
since “popup” is not plainly a String lets extract it to an object ,
3> Now popup contains an array of “menuitem”
So, we’ll have to extract it to a JSONArray,
JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); Since it contains 3 items lets put it in a for loop.
for (int i = 0; i < 3; i++) { System.out.println(menuitemArray.getJSONObject(i) .getString("value").toString()); System.out.println(menuitemArray.getJSONObject(i).getString( "onclick").toString()); }
Basically thats it , u should see the output in the DDMS
4> The full code is as below,
import org.json.JSONArray; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; public class JsonParser extends Activity { private JSONObject jObject; private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { parse(); } catch (Exception e) { e.printStackTrace(); } } private void parse() throws Exception { jObject = new JSONObject(jString); JSONObject menuObject = jObject.getJSONObject("menu"); String attributeId = menuObject.getString("id"); System.out.println(attributeId); String attributeValue = menuObject.getString("value"); System.out.println(attributeValue); JSONObject popupObject = menuObject.getJSONObject("popup"); JSONArray menuitemArray = popupObject.getJSONArray("menuitem"); for (int i = 0; i < 3; i++) { System.out.println(menuitemArray.getJSONObject(i) .getString("value").toString()); System.out.println(menuitemArray.getJSONObject(i).getString( "onclick").toString()); } } }
Friday, November 25, 2011
how to send Bean class object to ather activity using Parcelabel
to send from Activity A to Activity B
mCommentbutton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent i2=new Intent(AClass.this,BClass.class);
Bundle b3 = new Bundle();
//usercomments=new ArrayList<UserComments>();
b3.putParcelableArrayList("usercomments", usercomments);
i2.putExtras(b3);
startActivity(i2);
}
});
and BClass.java activity you can parse like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog);
Bundle b = getIntent().getExtras();
usercomments=b.getParcelableArrayList("usercomments");
}
Parsalabel class for UserComments will be like this:
import android.os.Parcel;
import android.os.Parcelable;
public class UserComments implements Parcelable {
public String profileid;
public String userComments;
public String name;
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(profileid);
dest.writeString(userComments);
dest.writeString(name);
}
public static final Parcelable.Creator<UserComments> CREATOR
= new Parcelable.Creator<UserComments>() {
public UserComments createFromParcel(Parcel in) {
return new UserComments(in);
}
public UserComments[] newArray(int size) {
return new UserComments[size];
}
};
public UserComments(Parcel in) {
if(in!=null){
profileid=in.readString();;
userComments=in.readString();
name=in.readString();
}
}
public UserComments() {
}
}
also you can do some thing like this:
Intent i1=new Intent(ProfilesList.this,ProfileInfo.class);
i1.putExtra("profileid", pid);
i1.putExtra("rating",mProfileRatings.get(position));
i1.putExtra("profilename",mProfileNames.get(position));
i1.putExtra("service_charge",serviceList.get(position).service_charge);
i1.putExtra("service_id", serviceList.get(position).service_id);
i1.putExtra("profiledes",mProfileDes.get(position));
i1.putParcelableArrayListExtra("comments", usercomments);
i1.putExtra("country", mProfileCountries.get(position));
i1.putExtra("city", mProfileCities.get(position));
startActivity(i1);
mCommentbutton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent i2=new Intent(AClass.this,BClass.class);
Bundle b3 = new Bundle();
//usercomments=new ArrayList<UserComments>();
b3.putParcelableArrayList("usercomments", usercomments);
i2.putExtras(b3);
startActivity(i2);
}
});
and BClass.java activity you can parse like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog);
Bundle b = getIntent().getExtras();
usercomments=b.getParcelableArrayList("usercomments");
}
Parsalabel class for UserComments will be like this:
import android.os.Parcel;
import android.os.Parcelable;
public class UserComments implements Parcelable {
public String profileid;
public String userComments;
public String name;
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(profileid);
dest.writeString(userComments);
dest.writeString(name);
}
public static final Parcelable.Creator<UserComments> CREATOR
= new Parcelable.Creator<UserComments>() {
public UserComments createFromParcel(Parcel in) {
return new UserComments(in);
}
public UserComments[] newArray(int size) {
return new UserComments[size];
}
};
public UserComments(Parcel in) {
if(in!=null){
profileid=in.readString();;
userComments=in.readString();
name=in.readString();
}
}
public UserComments() {
}
}
also you can do some thing like this:
Intent i1=new Intent(ProfilesList.this,ProfileInfo.class);
i1.putExtra("profileid", pid);
i1.putExtra("rating",mProfileRatings.get(position));
i1.putExtra("profilename",mProfileNames.get(position));
i1.putExtra("service_charge",serviceList.get(position).service_charge);
i1.putExtra("service_id", serviceList.get(position).service_id);
i1.putExtra("profiledes",mProfileDes.get(position));
i1.putParcelableArrayListExtra("comments", usercomments);
i1.putExtra("country", mProfileCountries.get(position));
i1.putExtra("city", mProfileCities.get(position));
startActivity(i1);
Friday, November 18, 2011
CustomDialog
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
<TableRow
android:id="@+id/tabrow_review">
<TextView android:id="@+id/yourreview" android:layout_width="wrap_content"
android:layout_height="70dip" android:text="Your Review"
android:gravity="center"
android:textStyle="bold"
android:layout_alignParentLeft="true"/>
<RatingBar android:id="@+id/ratingBar" style="?android:attr/ratingBarStyleSmall"
android:layout_gravity="center_vertical|center_horizontal"
android:focusable="true" android:layout_width="wrap_content"
android:layout_height="wrap_content"></RatingBar>
</TableRow>
</TableLayout>
review_rating.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="10dp"
android:id="@+id/layout_root">
<!-- <TextView android:id="@+id/comments" android:text="My Review Section"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
/>-->
<RatingBar android:id="@+id/reviewStars"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:numStars="5" android:stepSize="1" />
<TextView android:layout_width="fill_parent"
android:layout_height="10dip" />
<TextView android:layout_width="wrap_content"
android:layout_height="30dip"
android:layout_gravity="center"
android:id="@+id/rateval"/>
<TextView android:layout_width="fill_parent"
android:layout_height="10dip" />
<EditText android:id="@+id/reviewTitle"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:hint="Enter Title"
/>
<EditText android:id="@+id/reviewWriteText"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:ems="13" android:hint="Enter a comment"
android:singleLine="false" android:lines="5"
/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal">
<Button android:id="@+id/reviewWriteAccept" android:text="Submit Review"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_weight="1" />
<Button android:id="@+id/reviewWriteCancel" android:text="Close"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</ScrollView>
CustomDialog1Activity.java
package com.incept.customdialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class CustomDialog1Activity extends Activity {
static final int CUSTOM_DIALOG_ID = 0;
TextView customDialog_TextView,customDialog_Textval;
EditText customDialog_EditText;
Button customDialog_Update, customDialog_Dismiss;
RatingBar customDialog_Rating;
RatingBar outerrating;
String rating_value;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableRow review = (TableRow)findViewById(R.id.tabrow_review);
outerrating = (RatingBar)findViewById(R.id.ratingBar);
review.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID);
}
});
}
private Button.OnClickListener customDialog_UpdateOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
customDialog_TextView.setText(customDialog_EditText.getText().toString());
}
};
private Button.OnClickListener customDialog_DismissOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dismissDialog(CUSTOM_DIALOG_ID);
}
};
private RatingBar.OnRatingBarChangeListener customDialog_RatingOnClickListener
= new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar paramRatingBar, float rating,
boolean paramBoolean) {
//Toast.makeText(CustomDialog1Activity.this, "New Rating: " + rating, Toast.LENGTH_SHORT).show();
rating_value=Float.toString(rating);
customDialog_Textval.setText(rating_value);
outerrating.setRating(rating);
}
};
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Dialog dialog = null;;
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(CustomDialog1Activity.this);
dialog.setContentView(R.layout.review_rating);
dialog.setTitle("Review It!");
customDialog_EditText = (EditText)dialog.findViewById(R.id.reviewWriteText);
//customDialog_TextView = (TextView)dialog.findViewById(R.id.dialogtextview);
customDialog_Textval=(TextView)dialog.findViewById(R.id.rateval);
customDialog_Update = (Button)dialog.findViewById(R.id.reviewWriteAccept);
customDialog_Dismiss = (Button)dialog.findViewById(R.id.reviewWriteCancel);
customDialog_Rating = (RatingBar)dialog.findViewById(R.id.reviewStars);
customDialog_Update.setOnClickListener(customDialog_UpdateOnClickListener);
customDialog_Dismiss.setOnClickListener(customDialog_DismissOnClickListener);
customDialog_Rating.setOnRatingBarChangeListener(customDialog_RatingOnClickListener);
break;
}
return dialog;
}
}
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
>
<TableRow
android:id="@+id/tabrow_review">
<TextView android:id="@+id/yourreview" android:layout_width="wrap_content"
android:layout_height="70dip" android:text="Your Review"
android:gravity="center"
android:textStyle="bold"
android:layout_alignParentLeft="true"/>
<RatingBar android:id="@+id/ratingBar" style="?android:attr/ratingBarStyleSmall"
android:layout_gravity="center_vertical|center_horizontal"
android:focusable="true" android:layout_width="wrap_content"
android:layout_height="wrap_content"></RatingBar>
</TableRow>
</TableLayout>
review_rating.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:padding="10dp"
android:id="@+id/layout_root">
<!-- <TextView android:id="@+id/comments" android:text="My Review Section"
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:textSize="20sp"
android:textStyle="bold"
android:gravity="center"
/>-->
<RatingBar android:id="@+id/reviewStars"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:numStars="5" android:stepSize="1" />
<TextView android:layout_width="fill_parent"
android:layout_height="10dip" />
<TextView android:layout_width="wrap_content"
android:layout_height="30dip"
android:layout_gravity="center"
android:id="@+id/rateval"/>
<TextView android:layout_width="fill_parent"
android:layout_height="10dip" />
<EditText android:id="@+id/reviewTitle"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:hint="Enter Title"
/>
<EditText android:id="@+id/reviewWriteText"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:ems="13" android:hint="Enter a comment"
android:singleLine="false" android:lines="5"
/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="horizontal">
<Button android:id="@+id/reviewWriteAccept" android:text="Submit Review"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_weight="1" />
<Button android:id="@+id/reviewWriteCancel" android:text="Close"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="center"
android:layout_alignParentBottom="true"
android:layout_weight="1" />
</LinearLayout>
</LinearLayout>
</ScrollView>
CustomDialog1Activity.java
package com.incept.customdialog;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class CustomDialog1Activity extends Activity {
static final int CUSTOM_DIALOG_ID = 0;
TextView customDialog_TextView,customDialog_Textval;
EditText customDialog_EditText;
Button customDialog_Update, customDialog_Dismiss;
RatingBar customDialog_Rating;
RatingBar outerrating;
String rating_value;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TableRow review = (TableRow)findViewById(R.id.tabrow_review);
outerrating = (RatingBar)findViewById(R.id.ratingBar);
review.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
showDialog(CUSTOM_DIALOG_ID);
}
});
}
private Button.OnClickListener customDialog_UpdateOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
customDialog_TextView.setText(customDialog_EditText.getText().toString());
}
};
private Button.OnClickListener customDialog_DismissOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dismissDialog(CUSTOM_DIALOG_ID);
}
};
private RatingBar.OnRatingBarChangeListener customDialog_RatingOnClickListener
= new RatingBar.OnRatingBarChangeListener() {
@Override
public void onRatingChanged(RatingBar paramRatingBar, float rating,
boolean paramBoolean) {
//Toast.makeText(CustomDialog1Activity.this, "New Rating: " + rating, Toast.LENGTH_SHORT).show();
rating_value=Float.toString(rating);
customDialog_Textval.setText(rating_value);
outerrating.setRating(rating);
}
};
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Dialog dialog = null;;
switch(id) {
case CUSTOM_DIALOG_ID:
dialog = new Dialog(CustomDialog1Activity.this);
dialog.setContentView(R.layout.review_rating);
dialog.setTitle("Review It!");
customDialog_EditText = (EditText)dialog.findViewById(R.id.reviewWriteText);
//customDialog_TextView = (TextView)dialog.findViewById(R.id.dialogtextview);
customDialog_Textval=(TextView)dialog.findViewById(R.id.rateval);
customDialog_Update = (Button)dialog.findViewById(R.id.reviewWriteAccept);
customDialog_Dismiss = (Button)dialog.findViewById(R.id.reviewWriteCancel);
customDialog_Rating = (RatingBar)dialog.findViewById(R.id.reviewStars);
customDialog_Update.setOnClickListener(customDialog_UpdateOnClickListener);
customDialog_Dismiss.setOnClickListener(customDialog_DismissOnClickListener);
customDialog_Rating.setOnRatingBarChangeListener(customDialog_RatingOnClickListener);
break;
}
return dialog;
}
}
Thursday, November 17, 2011
Customised ListView
main.xml
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:stretchColumns="*" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/tbl">
<TableRow>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:src="@drawable/icon" />
<TextView android:layout_width="wrap_content" android:id="@+id/name_txt"
android:layout_height="wrap_content" android:text="Profile Name" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="100dp" android:gravity="center"
android:layout_height="wrap_content" android:text="Price"
android:id="@+id/price_txt" />
<TextView android:layout_width="100dp" android:gravity="center"
android:layout_height="wrap_content" android:text="Country"
android:id="@+id/country_txt"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- <RatingBar android:id="@+id/ratingBar1" android:fitsSystemWindows="false"
android:maxWidth="150dip" android:minHeight="23dip" android:maxHeight="25dip"
android:layout_height="40dp" android:layout_width="150dp" /> -->
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Time Slot"
android:layout_gravity="center_vertical|center_horizontal"
android:id="@+id/time" />
<RatingBar android:id="@+id/ratingBar" style="?android:attr/ratingBarStyleSmall"
android:layout_gravity="center_vertical|center_horizontal"
android:focusable="true" android:layout_width="wrap_content"
android:layout_height="wrap_content"></RatingBar>
</LinearLayout>
</TableRow>
</TableLayout>
clistview.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">
<ListView android:id="@+id/booklist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</ListView>
</LinearLayout>
Customlistview.java
package com.incept.customlist;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CustomlistviewActivity extends Activity {
static final ArrayList<HashMap<String,Object>> list =
new ArrayList<HashMap<String,Object>>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clistview);
ListView listview = (ListView)findViewById(R.id.booklist);
populateList();
listview.setAdapter(new myListAdapter(list,this));
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private void populateList() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", "Pramod");
map.put("price", "25$");
map.put("country", "India");
map.put("timeslot", "2");
map.put("rating", 3);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Chakri");
map.put("price", "10$");
map.put("country", "India");
map.put("timeslot", "2");
map.put("rating", 1);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Rajesh");
map.put("price", "50$");
map.put("country", "UK");
map.put("timeslot", "2");
map.put("rating", 5);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Tom");
map.put("price", "100$");
map.put("country", "US");
map.put("timeslot", "2");
map.put("rating", 4);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Pramod");
map.put("price", "50$");
map.put("country", "India");
map.put("timeslot", "2");
map.put("rating", 1);
list.add(map);
}
}
myListAdapter.java
package com.incept.customlist;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
class myListAdapter extends BaseAdapter {
ArrayList<HashMap<String,Object>> Profiles;
LayoutInflater layoutinflator;
myListAdapter(ArrayList<HashMap<String,Object>> books,Context con)
{
Profiles=books;
layoutinflator=LayoutInflater.from(con);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Profiles.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return Profiles.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder mviewholder;
if(convertView==null){
convertView=layoutinflator.inflate(R.layout.main, null);
mviewholder = new ViewHolder();
mviewholder.v1=(TextView)convertView.findViewById(R.id.name_txt);
mviewholder.v2=(TextView)convertView.findViewById(R.id.price_txt);
mviewholder.v3=(TextView)convertView.findViewById(R.id.country_txt);
mviewholder.v4=(TextView)convertView.findViewById(R.id.time);
mviewholder.b1=(RatingBar)convertView.findViewById(R.id.ratingBar);
convertView.setTag(mviewholder);
}
else{
mviewholder=(ViewHolder) convertView.getTag();
}
mviewholder.v1.setText((String) Profiles.get(position).get("name"));
mviewholder.v2.setText((String) Profiles.get(position).get("price"));
mviewholder.v3.setText((String) Profiles.get(position).get("country"));
mviewholder.v4.setText((String) Profiles.get(position).get("timeslot"));
mviewholder.b1.setRating((Integer) Profiles.get(position).get("rating"));
return convertView;
}
}
ViewHolder.java
package com.incept.customlist;
import android.widget.RatingBar;
import android.widget.TextView;
public class ViewHolder {
TextView v1;
TextView v2;
TextView v3;
TextView v4;
RatingBar b1;
}
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:stretchColumns="*" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/tbl">
<TableRow>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:src="@drawable/icon" />
<TextView android:layout_width="wrap_content" android:id="@+id/name_txt"
android:layout_height="wrap_content" android:text="Profile Name" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="100dp" android:gravity="center"
android:layout_height="wrap_content" android:text="Price"
android:id="@+id/price_txt" />
<TextView android:layout_width="100dp" android:gravity="center"
android:layout_height="wrap_content" android:text="Country"
android:id="@+id/country_txt"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<!-- <RatingBar android:id="@+id/ratingBar1" android:fitsSystemWindows="false"
android:maxWidth="150dip" android:minHeight="23dip" android:maxHeight="25dip"
android:layout_height="40dp" android:layout_width="150dp" /> -->
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Time Slot"
android:layout_gravity="center_vertical|center_horizontal"
android:id="@+id/time" />
<RatingBar android:id="@+id/ratingBar" style="?android:attr/ratingBarStyleSmall"
android:layout_gravity="center_vertical|center_horizontal"
android:focusable="true" android:layout_width="wrap_content"
android:layout_height="wrap_content"></RatingBar>
</LinearLayout>
</TableRow>
</TableLayout>
clistview.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">
<ListView android:id="@+id/booklist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</ListView>
</LinearLayout>
Customlistview.java
package com.incept.customlist;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CustomlistviewActivity extends Activity {
static final ArrayList<HashMap<String,Object>> list =
new ArrayList<HashMap<String,Object>>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.clistview);
ListView listview = (ListView)findViewById(R.id.booklist);
populateList();
listview.setAdapter(new myListAdapter(list,this));
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
private void populateList() {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("name", "Pramod");
map.put("price", "25$");
map.put("country", "India");
map.put("timeslot", "2");
map.put("rating", 3);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Chakri");
map.put("price", "10$");
map.put("country", "India");
map.put("timeslot", "2");
map.put("rating", 1);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Rajesh");
map.put("price", "50$");
map.put("country", "UK");
map.put("timeslot", "2");
map.put("rating", 5);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Tom");
map.put("price", "100$");
map.put("country", "US");
map.put("timeslot", "2");
map.put("rating", 4);
list.add(map);
map = new HashMap<String, Object>();
map.put("name", "Pramod");
map.put("price", "50$");
map.put("country", "India");
map.put("timeslot", "2");
map.put("rating", 1);
list.add(map);
}
}
myListAdapter.java
package com.incept.customlist;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.RatingBar;
import android.widget.TextView;
class myListAdapter extends BaseAdapter {
ArrayList<HashMap<String,Object>> Profiles;
LayoutInflater layoutinflator;
myListAdapter(ArrayList<HashMap<String,Object>> books,Context con)
{
Profiles=books;
layoutinflator=LayoutInflater.from(con);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Profiles.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return Profiles.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder mviewholder;
if(convertView==null){
convertView=layoutinflator.inflate(R.layout.main, null);
mviewholder = new ViewHolder();
mviewholder.v1=(TextView)convertView.findViewById(R.id.name_txt);
mviewholder.v2=(TextView)convertView.findViewById(R.id.price_txt);
mviewholder.v3=(TextView)convertView.findViewById(R.id.country_txt);
mviewholder.v4=(TextView)convertView.findViewById(R.id.time);
mviewholder.b1=(RatingBar)convertView.findViewById(R.id.ratingBar);
convertView.setTag(mviewholder);
}
else{
mviewholder=(ViewHolder) convertView.getTag();
}
mviewholder.v1.setText((String) Profiles.get(position).get("name"));
mviewholder.v2.setText((String) Profiles.get(position).get("price"));
mviewholder.v3.setText((String) Profiles.get(position).get("country"));
mviewholder.v4.setText((String) Profiles.get(position).get("timeslot"));
mviewholder.b1.setRating((Integer) Profiles.get(position).get("rating"));
return convertView;
}
}
ViewHolder.java
package com.incept.customlist;
import android.widget.RatingBar;
import android.widget.TextView;
public class ViewHolder {
TextView v1;
TextView v2;
TextView v3;
TextView v4;
RatingBar b1;
}
Thursday, November 3, 2011
Sending multipar request to server in Android (like image and data)
/**
* here list of user accounts and 6 phone numbers,6 emailids,and Service provicers information are sending .
* This method creates Account at server and returns acknowledge
* of creation of successful account.
* @throws JSONException
*/
public String getcreatedAccount(final String lid2, final String pwd2,final String uname,
final String city2,final String country2,
ArrayList<Phnos> mPhnolist,ArrayList<EmailIds> mEmailidlist,final String issp,final String refid,final String mcity,final String mcnt,final String pdes,ArrayList<Service1> serviceList,final String mid,final String memailid,final String mstreet,final String mpost,final String selectcat,String imgData) throws JSONException {
Log.e("mcity",""+mcity);
Log.e("pdes",""+pdes);
String mRes=null;
//mDBHelper =mAppMgr.getDbHelper();
//mRes = mDBHelper.createAccountfun(account) ;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("client", "mc"));
postParameters.add(new BasicNameValuePair("loginId", lid2));
postParameters.add(new BasicNameValuePair("password", pwd2));
postParameters.add(new BasicNameValuePair("profileName",uname));
if(mPhnolist.size()!=0){
//String json=jsonRequestConstructor(mPhnolist);
//postParameters.add(new BasicNameValuePair("phlist",json));
}
if(mEmailidlist.size()!=0){
//String json2=jsonRequestConstructorForemailid(mEmailidlist);
//postParameters.add(new BasicNameValuePair("emaillist",json2));
}
postParameters.add(new BasicNameValuePair("city",city2));
postParameters.add(new BasicNameValuePair("country",country2));
postParameters.add(new BasicNameValuePair("mailid_primary",mEmailidlist.get(0).emailid));
if(mEmailidlist.size()>=2){
postParameters.add(new BasicNameValuePair("mailid_other1",mEmailidlist.get(1).emailid));
}
if(mEmailidlist.size()>=3){
postParameters.add(new BasicNameValuePair("mailid_other2",mEmailidlist.get(2).emailid));
}
if(mEmailidlist.size()>=4){
postParameters.add(new BasicNameValuePair("mailid_other3",mEmailidlist.get(3).emailid));
}
if(mEmailidlist.size()>=5){
postParameters.add(new BasicNameValuePair("mailid_other4",mEmailidlist.get(4).emailid));
}
if(mEmailidlist.size()>=6){
postParameters.add(new BasicNameValuePair("mailid_other5",mEmailidlist.get(5).emailid));
}
postParameters.add(new BasicNameValuePair("type_primary",mPhnolist.get(0).phno));
if(mPhnolist.size()>=2){
postParameters.add(new BasicNameValuePair("type_other1",mPhnolist.get(1).phno));
}
if(mPhnolist.size()>=3){
postParameters.add(new BasicNameValuePair("type_other2",mPhnolist.get(2).phno));
}
if(mPhnolist.size()>=4){
postParameters.add(new BasicNameValuePair("type_other3",mPhnolist.get(3).phno));
}
if(mPhnolist.size()>=5){
postParameters.add(new BasicNameValuePair("type_other4",mPhnolist.get(4).phno));
}
if(mPhnolist.size()>=6){
postParameters.add(new BasicNameValuePair("type_other5",mPhnolist.get(5).phno));
}
postParameters.add(new BasicNameValuePair("reference_id",refid));
postParameters.add(new BasicNameValuePair("catalog_version_id",Integer.toString(mCatv)));
postParameters.add(new BasicNameValuePair("isServiceProvider",issp));
if(issp.equals("1")){
postParameters.add(new BasicNameValuePair("spProfileDesc",pdes));
if(serviceList.size()!=0){
postParameters.add(new BasicNameValuePair("service_name",serviceList.get(0).service_name));
Log.e("serviceList.get(0).service_name",""+serviceList.get(0).service_name);
postParameters.add(new BasicNameValuePair("service_desc",serviceList.get(0).service_des));
Log.e("serviceList.get(0).service_des",""+serviceList.get(0).service_des);
postParameters.add(new BasicNameValuePair("service_duration",serviceList.get(0).timeslot));//mcharge
Log.e("serviceList.get(0).timeslot",""+serviceList.get(0).timeslot);
postParameters.add(new BasicNameValuePair("service_charge",serviceList.get(0).service_charge));
Log.e("serviceList.get(0).service_charge",""+serviceList.get(0).service_charge);
}
postParameters.add(new BasicNameValuePair("merchant_acc_id",mid));
Log.e("merchant_acc_id",mid);
postParameters.add(new BasicNameValuePair("merchant_city",mcity));
Log.e("merchant_city",mcity);
postParameters.add(new BasicNameValuePair("merchant_emai_id",memailid));
Log.e("merchant_emai_id",memailid);
postParameters.add(new BasicNameValuePair("merchant_country",mcnt));
Log.e("merchant_country",""+mcnt);
postParameters.add(new BasicNameValuePair("merchant_street_add",mstreet));//mcharge
Log.e("mstreet",""+mstreet);
postParameters.add(new BasicNameValuePair("merchant_postal_code",mpost));
Log.e("merchant_postal_code",mpost);
postParameters.add(new BasicNameValuePair("select_category",selectcat));
Log.e("selectcat",""+selectcat);
}
String response = null;
try {
response = CustomHttpClient.executeHttpPost1(SM_SERVER_URL_PREFIX+"register", postParameters);
String res=response.toString();
mRes= res.replaceAll("\\s+","");
res1=new RegistrationRes();
res1=JSONSMParser.parseRegisrationstatus( mRes);
Log.e("res1.status_code",""+res1.status_code);
Log.e("login res",""+mRes);
}
catch (Exception e) {
Log.e("exception",e.toString());
}
return res1.status_code;
}
//following is supporting class for executeHttp request and response
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.net.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
private static Bitmap bitmap;
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
Log.e( "postParameters",""+ postParameters);
Log.e("formEntity",""+formEntity);
/* MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));*/
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//this bewlow code to send image and data with multipart request
public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
HttpPost post = new HttpPost(url);
Bitmap bitmap;
String Result_STR=null;
HttpClient client = new DefaultHttpClient();
HttpEntity resmarkMessagesReadFrom =null;
MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
Log.e("postParameters.size()",""+postParameters.size());
for(int i=0;i<postParameters.size();i++){
Log.e("parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());
reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));
if(postParameters.get(i).getName().equals("imgpath")){
bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue());
// you can change the format of you image compressed for what do you want;
//now it is set up to 640 x 480;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
reqmarkMessagesReadFrom.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));
}
post.setEntity(reqmarkMessagesReadFrom);
}
HttpResponse response = client.execute(post);
resmarkMessagesReadFrom = response.getEntity();
if (resmarkMessagesReadFrom != null) {
Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
// mMSGBox.setText(Result_STR);
}
}
finally {
}
return Result_STR;
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
* here list of user accounts and 6 phone numbers,6 emailids,and Service provicers information are sending .
* This method creates Account at server and returns acknowledge
* of creation of successful account.
* @throws JSONException
*/
public String getcreatedAccount(final String lid2, final String pwd2,final String uname,
final String city2,final String country2,
ArrayList<Phnos> mPhnolist,ArrayList<EmailIds> mEmailidlist,final String issp,final String refid,final String mcity,final String mcnt,final String pdes,ArrayList<Service1> serviceList,final String mid,final String memailid,final String mstreet,final String mpost,final String selectcat,String imgData) throws JSONException {
Log.e("mcity",""+mcity);
Log.e("pdes",""+pdes);
String mRes=null;
//mDBHelper =mAppMgr.getDbHelper();
//mRes = mDBHelper.createAccountfun(account) ;
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("client", "mc"));
postParameters.add(new BasicNameValuePair("loginId", lid2));
postParameters.add(new BasicNameValuePair("password", pwd2));
postParameters.add(new BasicNameValuePair("profileName",uname));
if(mPhnolist.size()!=0){
//String json=jsonRequestConstructor(mPhnolist);
//postParameters.add(new BasicNameValuePair("phlist",json));
}
if(mEmailidlist.size()!=0){
//String json2=jsonRequestConstructorForemailid(mEmailidlist);
//postParameters.add(new BasicNameValuePair("emaillist",json2));
}
postParameters.add(new BasicNameValuePair("city",city2));
postParameters.add(new BasicNameValuePair("country",country2));
postParameters.add(new BasicNameValuePair("mailid_primary",mEmailidlist.get(0).emailid));
if(mEmailidlist.size()>=2){
postParameters.add(new BasicNameValuePair("mailid_other1",mEmailidlist.get(1).emailid));
}
if(mEmailidlist.size()>=3){
postParameters.add(new BasicNameValuePair("mailid_other2",mEmailidlist.get(2).emailid));
}
if(mEmailidlist.size()>=4){
postParameters.add(new BasicNameValuePair("mailid_other3",mEmailidlist.get(3).emailid));
}
if(mEmailidlist.size()>=5){
postParameters.add(new BasicNameValuePair("mailid_other4",mEmailidlist.get(4).emailid));
}
if(mEmailidlist.size()>=6){
postParameters.add(new BasicNameValuePair("mailid_other5",mEmailidlist.get(5).emailid));
}
postParameters.add(new BasicNameValuePair("type_primary",mPhnolist.get(0).phno));
if(mPhnolist.size()>=2){
postParameters.add(new BasicNameValuePair("type_other1",mPhnolist.get(1).phno));
}
if(mPhnolist.size()>=3){
postParameters.add(new BasicNameValuePair("type_other2",mPhnolist.get(2).phno));
}
if(mPhnolist.size()>=4){
postParameters.add(new BasicNameValuePair("type_other3",mPhnolist.get(3).phno));
}
if(mPhnolist.size()>=5){
postParameters.add(new BasicNameValuePair("type_other4",mPhnolist.get(4).phno));
}
if(mPhnolist.size()>=6){
postParameters.add(new BasicNameValuePair("type_other5",mPhnolist.get(5).phno));
}
postParameters.add(new BasicNameValuePair("reference_id",refid));
postParameters.add(new BasicNameValuePair("catalog_version_id",Integer.toString(mCatv)));
postParameters.add(new BasicNameValuePair("isServiceProvider",issp));
if(issp.equals("1")){
postParameters.add(new BasicNameValuePair("spProfileDesc",pdes));
if(serviceList.size()!=0){
postParameters.add(new BasicNameValuePair("service_name",serviceList.get(0).service_name));
Log.e("serviceList.get(0).service_name",""+serviceList.get(0).service_name);
postParameters.add(new BasicNameValuePair("service_desc",serviceList.get(0).service_des));
Log.e("serviceList.get(0).service_des",""+serviceList.get(0).service_des);
postParameters.add(new BasicNameValuePair("service_duration",serviceList.get(0).timeslot));//mcharge
Log.e("serviceList.get(0).timeslot",""+serviceList.get(0).timeslot);
postParameters.add(new BasicNameValuePair("service_charge",serviceList.get(0).service_charge));
Log.e("serviceList.get(0).service_charge",""+serviceList.get(0).service_charge);
}
postParameters.add(new BasicNameValuePair("merchant_acc_id",mid));
Log.e("merchant_acc_id",mid);
postParameters.add(new BasicNameValuePair("merchant_city",mcity));
Log.e("merchant_city",mcity);
postParameters.add(new BasicNameValuePair("merchant_emai_id",memailid));
Log.e("merchant_emai_id",memailid);
postParameters.add(new BasicNameValuePair("merchant_country",mcnt));
Log.e("merchant_country",""+mcnt);
postParameters.add(new BasicNameValuePair("merchant_street_add",mstreet));//mcharge
Log.e("mstreet",""+mstreet);
postParameters.add(new BasicNameValuePair("merchant_postal_code",mpost));
Log.e("merchant_postal_code",mpost);
postParameters.add(new BasicNameValuePair("select_category",selectcat));
Log.e("selectcat",""+selectcat);
}
String response = null;
try {
response = CustomHttpClient.executeHttpPost1(SM_SERVER_URL_PREFIX+"register", postParameters);
String res=response.toString();
mRes= res.replaceAll("\\s+","");
res1=new RegistrationRes();
res1=JSONSMParser.parseRegisrationstatus( mRes);
Log.e("res1.status_code",""+res1.status_code);
Log.e("login res",""+mRes);
}
catch (Exception e) {
Log.e("exception",e.toString());
}
return res1.status_code;
}
//following is supporting class for executeHttp request and response
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.net.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
private static Bitmap bitmap;
/**
* Get our single instance of our HttpClient object.
*
* @return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* @param url The web address to post the request to
* @param postParameters The parameters to send via the request
* @return The result of the request
* @throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
Log.e( "postParameters",""+ postParameters);
Log.e("formEntity",""+formEntity);
/* MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
entity.addPart("returnformat", new StringBody("json"));
entity.addPart("uploaded", new ByteArrayBody(data,
"myImage.jpg"));*/
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//this bewlow code to send image and data with multipart request
public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
HttpPost post = new HttpPost(url);
Bitmap bitmap;
String Result_STR=null;
HttpClient client = new DefaultHttpClient();
HttpEntity resmarkMessagesReadFrom =null;
MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
Log.e("postParameters.size()",""+postParameters.size());
for(int i=0;i<postParameters.size();i++){
Log.e("parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());
reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));
if(postParameters.get(i).getName().equals("imgpath")){
bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue());
// you can change the format of you image compressed for what do you want;
//now it is set up to 640 x 480;
Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
// CompressFormat set up to JPG, you can change to PNG or whatever you want;
bmpCompressed.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
reqmarkMessagesReadFrom.addPart("myImage", new ByteArrayBody(data, "temp.jpg"));
}
post.setEntity(reqmarkMessagesReadFrom);
}
HttpResponse response = client.execute(post);
resmarkMessagesReadFrom = response.getEntity();
if (resmarkMessagesReadFrom != null) {
Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
// mMSGBox.setText(Result_STR);
}
}
finally {
}
return Result_STR;
}
/**
* Performs an HTTP GET request to the specified url.
*
* @param url The web address to post the request to
* @return The result of the request
* @throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Subscribe to:
Posts (Atom)