How to pass String array to webservice using ksoap2? - android

I am having a Web Client in Android using ksoap2 but I can't pass the string array as a parameter to the webservice.
Here's my code
String[] items={"hello","world"};
request.addproperty("str",items);

First use "soapUI" to see correct request structure(like item names,item namespaces , ...).
We assume that you want to write like this XML in request:(here n0 and n1 are namespaces)
<n0:strarray xmlns:n0="http://n0 ..." xmlns:n1="http://n1 ...">
<n1:string>hello</n1:string>
<n1:string>world</n1:string>
</n0:strarray>
extend a class from vector:
import java.util.Hashtable;
import java.util.Vector;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
public class StringArraySerializer extends Vector<String> implements KvmSerializable {
//n1 stores item namespaces:
String n1 = "http://n1 ...";
#Override
public Object getProperty(int arg0) {
return this.get(arg0);
}
#Override
public int getPropertyCount() {
return this.size();
}
#Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
arg2.setName = "string";
arg2.type = PropertyInfo.STRING_CLASS;
arg2.setNamespace = n1;
}
#Override
public void setProperty(int arg0, Object arg1) {
this.add(arg1.toString());
}
}
To build the request you have to do this:
1-make a new Vector-Object from this class:
StringArraySerializer stringArray = new StringArraySerializer();
2-then you can add elements:
stringArray.add("hello");
stringArray.add("world");
3-then you create a PropertyInfo with it:
//n0 stores array namespace:
String n0 = "http://n0 ...";
stringArrayProperty = new PropertyInfo();
stringArrayProperty.setName("strarray");
stringArrayProperty.setValue(stringArray);
stringArrayProperty.setType(stringArray.getClass());
stringArrayProperty.setNamespace(n0);
4-then you add all the properties to the request:
Request = new SoapObject(NAMESPACE, METHOD_NAME);
Request.addProperty(stringArrayProperty);
Reference:
ksoap2-android,CodingTipsAndTricks

it is like that you shold add it one by one.
public class ExtendedSoapObject extends SoapObject
{
public ExtendedSoapObject(String namespace, String name)
{
super(namespace, name);
}
public ExtendedSoapObject(SoapObject o)
{
super(o.getNamespace(), o.getName());
for (int i = 0; i < o.getAttributeCount(); i++)
{
AttributeInfo ai = new AttributeInfo();
o.getAttributeInfo(i, ai);
ai.setValue(o.getAttribute(i));
addAttribute(ai);
}
for (int i = 0; i < o.getPropertyCount(); i++)
{
PropertyInfo pi = new PropertyInfo();
o.getPropertyInfo(i, pi);
pi.setValue(o.getProperty(i));
addProperty(pi);
}
}
#Override
public SoapObject addProperty(String name, Object value)
{
if (value instanceof Object[])
{
Object[] subValues = (Object[]) value;
for (int i = 0; i < subValues.length; i++)
{
super.addProperty(name, subValues[i]);
}
}
else
{
super.addProperty(name, value);
}
return this;
}
#Override
public Object getProperty(String name)
{
List<Object> result = new ArrayList<Object>();
for (int i = 0; i < properties.size(); i++)
{
PropertyInfo prop = (PropertyInfo) properties.elementAt(i);
if (prop.getName() != null && prop.getName().equals(name))
{
result.add(unwrap(prop));
}
}
if (result.size() == 1)
{
return result.get(0);
}
else if (result.size() > 1)
{
return result.toArray(new Object[0]);
}
else
{
return null;
}
}
public Object[] getArrayProperty(String name)
{
Object o = getProperty(name);
Object values[] = null;
if (o != null)
{
if (o instanceof Object[])
{
values = (Object[]) o;
}
else
{
values = new Object[1];
values[0] = o;
}
}
return values;
}
Object unwrap(Object o)
{
if (o instanceof PropertyInfo)
{
return unwrap(((PropertyInfo) o).getValue());
}
else if (o instanceof SoapPrimitive || o instanceof SoapObject)
{
return o;
}
return null;
}
}

Related

finding in an array if specific fileds exists or not

This is my api
{}JSON
[]products
{}0
product-name : "Fiting"
product-id : "1"
product-description : "Door"
product-image : "https://image/logo.jpg"
product-categoryid : "2"
category-name : "Furniture"
{}1
product-name : "Bathroom"
product-id : "2"
product-description : "Services"
product-image : "https://image/logo.jpg"
product-categoryid : "1"
category-name : "Plumber"
subcategory-id : "1"
subcategory-name : "Bathroom"
subCategoryDetailModelClass.setSubCategoryId(productObject.getInt("subcategory-id"));
subCategoryDetailModelClass.setSubCategoryName(productObject.getString("subcategory-name"));
i cannot add subcategory-id,subcategory-name in my arraylist since it is not available at 0th position.....so how to check condition that if in api subcategory-id,subcategory-name is not available add other items in the list
StringRequest stringRequest = new StringRequest(Request.Method.GET,URLs.productURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("zsded", response.toString());
try {
JSONObject obj = new JSONObject(response);
JSONArray productArray = obj.getJSONArray("products");
//now looping through all the elements of the json array
for (int i = 0; i < productArray.length(); i++) {
JSONObject productObject = productArray.getJSONObject(i);
SubCategoryDetailModelClass subCategoryDetailModelClass = new SubCategoryDetailModelClass();
// if(productObject.getInt("subcategory-id"))
subCategoryDetailModelClass.setProduct_name(productObject.getString("product-name"));
subCategoryDetailModelClass.setProduct_id(productObject.getInt("product-id"));
subCategoryDetailModelClass.setProduct_desc(productObject.getString("product-description"));
subCategoryDetailModelClass.setProduct_imgURL(productObject.getString("product-image"));
subCategoryDetailModelClass.setProduct_CategoryId(productObject.getInt("product-categoryid"));
subCategoryDetailModelClass.setProduct_Category_Name(productObject.getString("category-name"));
subCategoryDetailModelClass.setSubCategoryId(productObject.getInt("subcategory-id"));
subCategoryDetailModelClass.setSubCategoryName(productObject.getString("subcategory-name"));
subCategoryListDetailModelClassArray.add(subCategoryDetailModelClass);
Log.d("subcatdetail", String.valueOf(subCategoryDetailModelClass));
}
Use this class
public class JSONHelper {
public static String getString(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
return json.getString(tag);
}
return "";
}
public static int getInt(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
if(json.get(tag) instanceof String) {
if(json.getString(tag).equalsIgnoreCase("None")) {
return -1;
}
if(!json.getString(tag).equals("")) {
return Integer.parseInt(json.getString(tag));
} else {
return -1;
}
}
return json.getInt(tag);
}
return -1;
}
public static boolean getBoolean(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
Object value = json.get(tag);
if(value instanceof String) {
return PrimitiveHelper.StringToBoolean((String) value);
} else if (value instanceof Integer) {
return PrimitiveHelper.IntegerToBoolean((int)value);
}
return json.getBoolean(tag);
}
return false;
}
public static Boolean getBooleanBoxed(JSONObject json, String tag) throws JSONException {
if(mJSONValueAvailable(json, tag)) {
Object value = json.get(tag);
if(value instanceof String) {
return PrimitiveHelper.StringToBooleanBoxed((String) value);
} else if (value instanceof Integer) {
return PrimitiveHelper.IntegerToBooleanBoxed((int) value);
}
return json.getBoolean(tag);
}
return null;//false;
}
private static boolean mJSONValueAvailable(JSONObject json, String tag) {
return json.has(tag) && !json.isNull(tag);
}
// private static Boolean mJSONValueAvailableBoxed(JSONObject json, String tag) {
// return json.has(tag) && !json.isNull(tag);//
// }
public static JSONArray sortJsonArray(JSONArray array, String sort) {
final String sortKey = sort;
//Logger.d("sortJSONArray by::: " + sortKey);
List<JSONObject> jsons = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsons.add(array.getJSONObject(i));
}
Collections.sort(jsons, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject lhs, JSONObject rhs) {
try {
String lid = lhs.getString(sortKey);
String rid = rhs.getString(sortKey);
// Here you could parse string id to integer and then compare.
return lid.compareTo(rid);
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
});
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONArray(jsons);
}
}
Call this as follows
subCategoryDetailModelClass.setProduct_name(JSONHelper.getString(productObject, "product-name"));
subCategoryDetailModelClass.setProduct_id(JSONHelper.getInt(productObject,"product-id"));
subCategoryDetailModelClass.setProduct_desc(JSONHelper.getString(productObject, "product-description"));
subCategoryDetailModelClass.setProduct_imgURL(JSONHelper.getString(productObject, "product-image"));
subCategoryDetailModelClass.setProduct_CategoryId(JSONHelper.getInt(productObject,"product-categoryid"));
subCategoryDetailModelClass.setProduct_Category_Name(JSONHelper.getString(productObject, "category-name"));
subCategoryDetailModelClass.setSubCategoryId(JSONHelper.getInt(productObject, "subcategory-id"));
subCategoryDetailModelClass.setSubCategoryName(JSONHelper.getString(productObject,"subcategory-name"));
subCategoryListDetailModelClassArray.add(subCategoryDetailModelClass);
Use Opt methods, For e.g.
optInt(String name, int fallback)
Returns the value mapped by name if it exists and is an int or can be
coerced to an int, or fallback otherwise.
There are optMethods for mostly primitive datatypes, check here

How to access the ArrayList present in Adapter in Activity

I have a listview in which in each row I have a checkbox along with details o persons. Now on clicking checkboxes, I want to store the id of those persons in arrayList which I am able to store but the arrayList id in adapter. I want to access the arrayList in activity because I want to take a button in activity on clicking which I want to send ids of all the selected persons to another activity. How do I do that.
My code is below:
SendWorkList.java
public class SendWorkList extends AppCompatActivity {
List<SendWorkRow> send_work_array_list;
ListView send_work_list;
JSONArray send_work_jsonArray1,send_work_result_jsonArray2;
JSONObject send_work_jsonObject1,send_work_result_jsonArray2_i;
String[] send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
String send_work_status,send_work_result;
ViewGroup send_work_headerView;
Set<Integer> send_work_count;
Intent intent;
Set<String> indexes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_work);
send_work_list=findViewById( R.id.send_work_list);
send_work_array_list=new ArrayList<SendWorkRow>();
send_work_count= new HashSet<>();
}
#Override
protected void onResume() {
super.onResume();
cardDetailsList();
/* send_work_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SendWorkList.this, "assasa", Toast.LENGTH_SHORT).show();
}
});*/
}
private void cardDetailsList()
{
RequestQueue rq = Volley.newRequestQueue(SendWorkList.this);
StringRequest stringRequest = new StringRequest( Request.Method.GET,
"http://grepthorsoftware.in/tst/bank_account/showingdata.php",
new Response.Listener<String>() {
public void onResponse(String response) {
try {
send_work_jsonArray1=new JSONArray(response);
send_work_jsonObject1 = send_work_jsonArray1.getJSONObject(0);
send_work_status= send_work_jsonObject1.getString("status");
if(send_work_status.equals("1")) {
send_work_result = send_work_jsonObject1.getString("result");
send_work_result_jsonArray2 = new JSONArray(send_work_result);
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
if ( send_work_name.length > 0 || send_work_id.length > 0 || send_work_bankaccount.length > 0 || send_work_ifsc.length > 0 || send_work_contacts.length > 0)
{
send_work_id = null;
send_work_name = null;
send_work_bankaccount = null;
send_work_ifsc = null;
send_work_contacts = null;
send_work_department= null;
send_work_cardnumber= null;
send_work_cardexpiry= null;
send_work_cardcvv= null;
send_work_id = new String[send_work_result_jsonArray2.length()];
send_work_name = new String[send_work_result_jsonArray2.length()];
send_work_bankaccount = new String[send_work_result_jsonArray2.length()];
send_work_ifsc = new String[send_work_result_jsonArray2.length()];
send_work_contacts = new String[send_work_result_jsonArray2.length()];
send_work_department =new String[send_work_result_jsonArray2.length()];
send_work_cardnumber = new String[send_work_result_jsonArray2.length()];
send_work_cardexpiry = new String[send_work_result_jsonArray2.length()];
send_work_cardcvv= new String[send_work_result_jsonArray2.length()];
}
for(int i=0;i<send_work_result_jsonArray2.length();i++)
{
send_work_result_jsonArray2_i=send_work_result_jsonArray2.getJSONObject(i);
send_work_id[i] = send_work_result_jsonArray2_i.getString("id");
send_work_name[i] = send_work_result_jsonArray2_i.getString("Name");
send_work_bankaccount[i] = send_work_result_jsonArray2_i.getString("Bankaccount");
send_work_ifsc[i] = send_work_result_jsonArray2_i.getString("IFSC");
send_work_contacts[i] = send_work_result_jsonArray2_i.getString("Contact");
send_work_department[i] = send_work_result_jsonArray2_i.getString("Department");
send_work_cardnumber[i] = send_work_result_jsonArray2_i.getString("Cardnumber");
send_work_cardexpiry[i] = send_work_result_jsonArray2_i.getString("Cardexpiry");
send_work_cardcvv[i] = send_work_result_jsonArray2_i.getString("Cardcvv");
}
if ( send_work_array_list.size() > 0) {
send_work_array_list.clear();
}
for (int i = 0; i < send_work_id.length && i< send_work_name.length && i < send_work_bankaccount.length && i < send_work_ifsc.length && i < send_work_contacts.length && i < send_work_department.length && i< send_work_cardnumber.length && i< send_work_cardexpiry.length && i< send_work_cardcvv.length; i++) {
send_work_array_list.add(new SendWorkRow( send_work_id[i], send_work_name[i], send_work_bankaccount[i], send_work_ifsc[i], send_work_contacts[i], send_work_department[i], send_work_cardnumber[i], send_work_cardexpiry[i],send_work_cardcvv[i]));
}
if ( send_work_headerView != null) {
send_work_list.removeHeaderView( send_work_headerView);
}
send_work_headerView = (ViewGroup) getLayoutInflater().inflate(R.layout.send_work_list_view_header, send_work_list, false);
send_work_list.addHeaderView( send_work_headerView);
send_work_list.setAdapter(new SendWorkAdapter(SendWorkList.this, send_work_array_list));
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError arg0) {
// TODO Auto-generated method stub
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
rq.add(stringRequest);
}
}
SendWorkAdapter.java
public class SendWorkAdapter extends BaseAdapter {
Context context;
List<SendWorkRow> send_work_array_list;
Set<String> indexes;
public SendWorkAdapter(Context context, List<SendWorkRow> send_work_array_list)
{
this.context=context;
this.send_work_array_list=send_work_array_list;
indexes = new HashSet<String>();
}
#Override
public int getCount() {
return send_work_array_list.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater= (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View view=inflater.inflate( R.layout.send_work_list_view_row,viewGroup,false);
CheckBox textView1=view.findViewById( R.id.send_work_checkbox_row);
TextView textView2=view.findViewById( R.id.send_work_name_row );
TextView textView3=view.findViewById( R.id.send_work_bank_account_row );
TextView textView4=view.findViewById( R.id.send_work_ifsc_row );
TextView textView5=view.findViewById( R.id.send_work_contact_number_row );
TextView textView6=view.findViewById( R.id.send_work_department_row );
TextView textView7=view.findViewById( R.id.send_work_card_number_row );
TextView textView8=view.findViewById( R.id.send_work_expiry_date_row );
TextView textView9=view.findViewById( R.id.send_work_cvv_row );
final SendWorkRow account_details_row=send_work_array_list.get( position );
textView2.setText( account_details_row.getSendWorkCardDetailsName() );
textView3.setText( account_details_row.getSendWorkCardDetailsBankAccount() );
textView4.setText( account_details_row.getSendWorkCardDetailsIfsc());
textView5.setText( account_details_row.getSendWorkCardDetailsContacts() );
textView6.setText( account_details_row.getSendWorkCardDetailsDepartment() );
textView7.setText( account_details_row.getSendWorkCardDetailsCardNumber() );
textView8.setText( account_details_row.getSendWorkCardDetailsCardExpiry() );
textView9.setText( account_details_row.getSendWorkCardDetailsCardCvv() );
textView1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(compoundButton.isChecked()){
Toast.makeText(context, account_details_row.getSendWorkCardDetailsId(), Toast.LENGTH_SHORT).show();
indexes.add(account_details_row.getSendWorkCardDetailsId());
}
}
});
return view;
}
}
SendWorkRow.java
public class SendWorkRow {
private String send_work_id,send_work_name,send_work_bankaccount,send_work_ifsc,send_work_contacts,send_work_department,send_work_cardnumber,send_work_cardexpiry,send_work_cardcvv;
public SendWorkRow(String send_work_id, String send_work_name, String send_work_bankaccount, String send_work_ifsc, String send_work_contacts,String send_work_department,String send_work_cardnumber,String send_work_cardexpiry,String send_work_cardcvv) {
this.send_work_id = send_work_id;
this.send_work_name = send_work_name;
this.send_work_bankaccount = send_work_bankaccount;
this.send_work_ifsc = send_work_ifsc;
this.send_work_contacts = send_work_contacts;
this.send_work_department = send_work_department;
this.send_work_cardnumber = send_work_cardnumber;
this.send_work_cardexpiry = send_work_cardexpiry;
this.send_work_cardcvv = send_work_cardcvv;
}
//Getters
public String getSendWorkCardDetailsId() {
return send_work_id;
}
public String getSendWorkCardDetailsName() {
return send_work_name;
}
public String getSendWorkCardDetailsBankAccount() {
return send_work_bankaccount;
}
public String getSendWorkCardDetailsIfsc() {
return send_work_ifsc;
}
public String getSendWorkCardDetailsContacts() {
return send_work_contacts;
}
public String getSendWorkCardDetailsDepartment() {
return send_work_department;
}
public String getSendWorkCardDetailsCardNumber() {
return send_work_cardnumber;
}
public String getSendWorkCardDetailsCardExpiry() {
return send_work_cardexpiry;
}
public String getSendWorkCardDetailsCardCvv() {
return send_work_cardcvv;
}
}
Create one method in adapter like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllWorkRows() {
return send_work_array_list;
}
}
and access this method using adapter instance in activity.
Another way is you can write a method in Adapter where you will find all selected ids in a List and return. So whenever you will require list of selected ids, call this method from Activity and do your task. like
public class SendWorkAdapter extends BaseAdapter {
public List<SendWorkRow> getAllSelectedWorkRows() {
// write your logic to find selected rows
return result;
}
}

Appending data to list

I am displaying data from two different API calls inside suggestion list so I'm calling two API's inside onQueryTextChange() .Since I am getting response from two different api calls i am using addAll() to append response from different apis.But data is not added and size of list is zero.But if i use searchResponses= (List<UserVideo>) response; then data is added to list but two different responses is not appended.Where am i going wrong?
#Override
public boolean onQueryTextChange(String s)
{
if(s.length()>=1) {
String mStart = "";
int mCount = 10;
String[] columnNames = {"_id", "name", "userImage", "location"};
final String[] temp = new String[4];
final MatrixCursor cursor = new MatrixCursor(columnNames);
SearchAPI.getSearchFeed(getApplicationContext(), s, mStart, mCount, mSettingsManager.getInstance().getAccessToken(), new APIResponseListener() {
#Override
public void onResponse(Object response) {
searchResponses.addAll((List<UserVideo>) response);
for (UserVideo searchResponse :searchResponses)
{searchResponse.setIsVideo(true);
temp[0] = Long.toString(id++);
temp[1] = searchResponse.getCaption();
temp[3] = searchResponse.getLocation();
cursor.addRow(temp);
}
mSearchView.setSuggestionsAdapter(new SearchListAdapter(HomeActivity.this, cursor));
}
#Override
public void onError(VolleyError error) {
if (error instanceof NoConnectionError) {
}
}
});
SearchAPI.getSearchUser(getApplicationContext(), s,mSettingsManager.getInstance().getAccessToken(), new APIResponseListener() {
#Override
public void onResponse(Object response)
{
searchResponses.addAll((List<UserVideo>) response);
for (UserVideo searchResponse :searchResponses) {
searchResponse.setIsVideo(false);
temp[0] = Long.toString(id++);
temp[1] = searchResponse.getUserName2();
temp[3] = searchResponse.getName();
cursor.addRow(temp);
}
mSearchView.setSuggestionsAdapter(new SearchListAdapter(HomeActivity.this, cursor));
}
#Override
public void onError(VolleyError error)
{
if (error instanceof NoConnectionError) {
}
}
});
}
return true;
}
Updated according to DavidJohns answer-
public boolean onQueryTextChange(String s)
{
if(s.length()>=0) {
String mStart = "";
int mCount = 10;
String[] columnNames = {"_id", "name", "userImage", "location"};
final String[] temp = new String[4];
final MatrixCursor cursor = new MatrixCursor(columnNames);
SearchAPI.getSearchFeed(getApplicationContext(), s, mStart, mCount, mSettingsManager.getInstance().getAccessToken(), new APIResponseListener() {
#Override
public void onResponse(Object response) {
searchResponses= (List<UserVideo>) response;
for (UserVideo searchResponse :searchResponses)
{
searchResponse.setIsVideo(true);
temp[0] = Long.toString(id++);
temp[1] = searchResponse.getCaption();
temp[2] = searchResponse.getUserId();
temp[3] = searchResponse.getLocation();
cursor.addRow(temp);
}
mSearchView.setSuggestionsAdapter(new SearchListAdapter(HomeActivity.this, cursor));
}
#Override
public void onError(VolleyError error) {
if (error instanceof NoConnectionError) {
}
}
});
SearchAPI.getSearchUser(getApplicationContext(), s,mSettingsManager.getInstance().getAccessToken(), new APIResponseListener() {
#Override
public void onResponse(Object response)
{
searchUserResponses= (List<UserVideo>) response;
for (UserVideo searchResponse :searchUserResponses) {
searchResponse.setIsVideo(false);
temp[0] = Long.toString(id++);
temp[1] = searchResponse.getUserName2();
temp[2] = searchResponse.getUserId();
temp[3] = searchResponse.getName();
searchResponses.add(searchResponse);
cursor.addRow(temp);
}
mSearchView.setSuggestionsAdapter(new SearchListAdapter(HomeActivity.this, cursor));
}
#Override
public void onError(VolleyError error)
{
if (error instanceof NoConnectionError) {
}
}
});
}
return true;
}
#Override
public boolean onSuggestionClick(int i)
{
if((searchResponses!=null)&&(searchResponses.get(i).getIsVideo()))
{
UserVideo searchResponse = searchResponses.get(i);
setSearchVideoToShow(searchResponse);
switchFragment(HomeActivity.FRAGMENT_VIDEO_SEARCH, false, "Video Details");
}
else if((searchResponses!=null)&&(!searchResponses.get(i).getIsVideo()))
{
mSingleClickHandle.put(ENABLE_FRAGMENT_SEARCH_VIEW, false);
setUserIdToShow(searchResponses.get(i).getUserId2());
closeDrawer();
switchFragment(HomeActivity.FRAGMENT_PROFILE_VIEW, false, "video");
}
return true;
}
Call your web services separatly and locate those results in two different lists,
then copy those list values into searchResponses.
you can merge the results as follows if their type is equal,
for(int i = 0; i < searchFeedList.size() ; i ++)
{
searchResponses.add(searchFeedList.get(i);
}
int totalSoze = searchFeedList.size() + searchUserList.size();
for(int j = searchFeedList.size(); j < totalSoze.size() ; j ++)
{
searchResponses.add(searchUserList.get(j);
}

Parcelable creation from a bundle does not call constructor

I have a class that implements Parcelable.
I safe this object to the bundle in an activites onSaveInstanceState and I try to recreate the object in onCreate. This looks like following:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
{
// this line does NOT call my constructor, why not?
// AND I don't get the same object as before => I get an uninitialised object
mStackManager = savedInstanceState.getParcelable(BackstackManager.TAG);
// the list and map in the object are NULL after this...
}
else
{
mStackManager = new BackstackManager();
...
}
}
#Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putParcelable(BackstackManager.TAG, mStackManager);
}
When the Parcelable class is created, it should call the cosntructor of the parcelable class, shouldn't it? My parcelable class is retrieved from the bundle, but it does not look like the object that was saved, it even is not initialised...
My simplified parcelable class looks like following:
public class BackstackManager implements Parcelable
{
public static final String TAG = BackstackManager.class.getName();
private List<List<Pair<Class<?>, Pair<Integer, String>>>> mBackstack;
private Map<String, Fragment.SavedState> mSavedStateMap;
public BackstackManager()
{
init();
}
private void init()
{
mBackstack = new ArrayList<List<Pair<Class<?>, Pair<Integer, String>>>>();
mSavedStateMap = new HashMap<String, Fragment.SavedState>();
}
// ----------------------
// Parcelable
// ----------------------
public static final Parcelable.Creator<BackstackManager> CREATOR =
new Parcelable.Creator<BackstackManager>()
{
#Override
public BackstackManager createFromParcel(Parcel source)
{
return new BackstackManager(source);
}
#Override
public BackstackManager[] newArray(int size)
{
return new BackstackManager[size];
}
};
public BackstackManager(Parcel source)
{
init();
readFromParcel(source);
}
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
dest.writeInt(mBackstack.size());
for (int i = 0; i < mBackstack.size(); i++)
{
List<Pair<Class<?>, Pair<Integer, String>>> data = mBackstack.get(i);
dest.writeInt(data.size());
for (int j = 0; j < data.size(); j++)
{
Class<?> clazz = data.get(j).first;
Integer id = data.get(j).second.first;
String tag = data.get(j).second.second;
Fragment f = mFragmentManager.findFragmentByTag(tag);
// 1) save backstack data
ParcelBundleUtils.writeStringNullSafe(dest, clazz != null ? clazz.getName() : null);
dest.writeInt(id);
dest.writeString(tag);
// 2) save fragment state, if possible
ParcelBundleUtils.writeBoolean(dest, f != null);
if (f != null)
ParcelBundleUtils.writeParcelableNullSafe(dest, mFragmentManager.saveFragmentInstanceState(f), 0);
}
}
}
public void readFromParcel(Parcel source)
{
int backstackSize = source.readInt();
for (int i = 0; i < backstackSize; i++)
{
ArrayList<Pair<Class<?>, Pair<Integer, String>>> data = new ArrayList<Pair<Class<?>, Pair<Integer, String>>>();
int dataSize = source.readInt();
for (int j = 0; j < dataSize; j++)
{
// 1) read backstack data
String clazzName = ParcelBundleUtils.readStringNullSafe(source);
Class<?> clazz = null;
if (clazzName != null)
{
try
{
clazz = Class.forName(clazzName);
}
catch (ClassNotFoundException e)
{
L.e(this, e);
}
}
Integer id = source.readInt();
String tag = source.readString();
// 2) read fragment state if possible
boolean savedStateExists = ParcelBundleUtils.readBoolean(source);
if (savedStateExists)
{
SavedState state = ParcelBundleUtils.readParcelableNullSafe(source, SavedState.class.getClassLoader());
if (state != null)
mSavedStateMap.put(tag, state);
}
data.add(new Pair<Class<?>, Pair<Integer, String>>(clazz, new Pair<Integer, String>(id, tag)));
}
mBackstack.add(data);
}
}
}
My ParcelBundleUtils just write a bit if an object is null or not and dependent on that read/write the actual object...
EDIT
my current workround is to use a read/write function for a bundle that does EXACTLY (I copy and pasted my code and just replaced the read/write functions) the same as the parcel read/write function, but writes the data directly to a bundle... But I really would like to know, why the above is not working as a parcel
EDIT 2
I found following: Android: Parcelable.writeToParcel and Parcelable.Creator.createFromParcel are never called
But if that's the problem, I would not be the only one facing this problem...
You must have the following line as the first line in your onCreate(Bundle) override:
super.onCreate(savedInstanceState);
This is why your state is not working correctly.

How to send object in ksoap2 request

I'm trying to pass an object to web service using ksopa2 library. I'm trying something like this:
RangeInfo controllingArea = new RangeInfo();
controllingArea.setLow(txtControllingAreaSearch.getText().toString());
PropertyInfo propertyControllingArea = new PropertyInfo();
propertyControllingArea.setType(new RangeInfo().getClass());
propertyControllingArea.setName("IControllingarea");
propertyControllingArea.setValue(controllingArea);
request.addProperty(propertyControllingArea);
PropertyInfo maxNoOfHits = new PropertyInfo();
maxNoOfHits.setValue(txtMaxNoHitsSearch.getText().toString());
maxNoOfHits.setName("IMaxnoofhits");
maxNoOfHits.setType(PropertyInfo.INTEGER_CLASS);
request.addProperty(maxNoOfHits);
My RangeInfo class is like this:
public String sign = "I";
public String option = "EQ";
public String low;
public String high;
public RangeInfo(){}
public RangeInfo(SoapObject soapObject)
{
if (soapObject == null)
return;
if (soapObject.hasProperty("Sign"))
{
Object obj = soapObject.getProperty("Sign");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j =(SoapPrimitive) obj;
sign = j.toString();
}else if (obj!= null && obj instanceof String){
sign = (String) obj;
}
}
if (soapObject.hasProperty("Option"))
{
Object obj = soapObject.getProperty("Option");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j =(SoapPrimitive) obj;
option = j.toString();
}else if (obj!= null && obj instanceof String){
option = (String) obj;
}
}
if (soapObject.hasProperty("Low"))
{
Object obj = soapObject.getProperty("Low");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j =(SoapPrimitive) obj;
low = j.toString();
}else if (obj!= null && obj instanceof String){
low = (String) obj;
}
}
if (soapObject.hasProperty("High"))
{
Object obj = soapObject.getProperty("High");
if (obj != null && obj.getClass().equals(SoapPrimitive.class)){
SoapPrimitive j =(SoapPrimitive) obj;
high = j.toString();
}else if (obj!= null && obj instanceof String){
high = (String) obj;
}
}
}
#Override
public Object getProperty(int arg0) {
switch(arg0){
case 0:
return sign;
case 1:
return option;
case 2:
return low;
case 3:
return high;
}
return null;
}
#Override
public int getPropertyCount() {
return 4;
}
#Override
public void getPropertyInfo(int index, #SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info) {
switch(index){
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Sign";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Option";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Low";
break;
case 3:
info.type = PropertyInfo.STRING_CLASS;
info.name = "High";
break;
}
}
#Override
public void setProperty(int arg0, Object arg1) {
}
public void setSign(String sign) {
this.sign = sign;
}
public void setOption(String option) {
this.option = option;
}
public void setLow(String low) {
this.low = low;
}
public void setHigh(String high) {
this.high = high;
}
In the server side I'm getting value of "IMaxnoofhits" variable, but "IControllingarea" is always null!!!
Someone has passed or imagine what could be the problem?
Thanks!
It looks to me like when you instantiate your RangeInfo controllingArea = new RangeInfo(); class you're not passing in a SoapObject so you're just calling the empty constructor, instead of the second constructor which has all your code.
Also, I know this isn't a part of your question but your maxNoOfHits parameter is set to the Integer class, even though .setValue looks like you're passing in a String.
Thanks guys,
I solved it by my self. Here is what i did. And it is working to send complex object to the request.
RangeInfo controllingArea = new RangeInfo();
controllingArea.setLow("Value");
controllingArea.setHigh("Value");
PropertyInfo item = new PropertyInfo();
item.setType(controllingArea.getClass());
item.setName("item");
item.setValue(controllingArea);
SoapObject object1 = new SoapObject("","IControllingarea");
object1.addProperty(item);
request.addSoapObject(object1);
PropertyInfo maxNoOfHits = new PropertyInfo();
maxNoOfHits.setValue(txtMaxNoHitsSearch.getText().toString());
maxNoOfHits.setName("IMaxnoofhits");
maxNoOfHits.setType(PropertyInfo.INTEGER_CLASS);
request.addProperty(maxNoOfHits);
Best regards.

Categories

Resources