How to set a Toast inside Ksoap Exception - android

I'm trying to set a Toast when Ksoap get an exception on IOexception or XmlPullParserException. I'm trying with this code in EXCEPTION but i can't show toast.. i guess it's beacuse application got crashed and there is no time to show toast, but I'm not sure... need a help! thank you in advance:
public class RequestWS extends Activity {
private static final String NAMESPACE = "-------";
private static String URL="http://-------";
private static final String METHOD_NAME_SYNCHROAP = "-----";
private static final String SOAP_ACTION_SYNCHROAP = "-----";
private SoapObject request=null;
private SoapSerializationEnvelope envelope=null;
private Object resultsRequestSOAP=null;
public String requestSession() {
request = new SoapObject(NAMESPACE, METHOD_NAME_SESSION);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE transporte = new HttpTransportSE(URL);
try {
transporte.call(SOAP_ACTION_SESSION, envelope);
resultsRequestSOAP = (Object)envelope.getResponse();
} catch (IOException e) {
RequestWS.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "ERROR", Toast.LENGTH_SHORT).show();
}
});
e.printStackTrace();
} catch (XmlPullParserException e) {
// NEED THE CORRECT CODE HERE
Toast.makeText(this, "ERROR", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
String strJSON = resultsRequestSOAP.toString();
return strJSON;
}
}
I also tried this code inside EXCEPTION, but still not working
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "ERROR", Toast.LENGTH_SHORT).show();
}
});

runOnUiThread should have done the task.
One more thing you can try.
Declare a Handler inside your activity and pass it to this function.
public String requestSession(final Handler handler) {
...
} catch (IOException e) {
// NEED THE CORRECT CODE HERE'
handler.post(new Runnable(){
Toast.makeText(this, "ERROR", Toast.LENGTH_LONG).show();
});
e.printStackTrace();
} catch (XmlPullParserException e) {
// NEED THE CORRECT CODE HERE
handler.post(new Runnable(){
Toast.makeText(this, "ERROR", Toast.LENGTH_LONG).show();
});
e.printStackTrace();
}
...
}

Related

Android Studio Webservice call "HTTP request failed, HTTP status: 401" Unauthorized

i try to connect my Android application to a Webservice.
I wrote a new class and defined some Variables:
I´ve got the Async Class to use the Network
class GetValueTask extends AsyncTask<ApiConnector,Long,String> {
#Override
protected String doInBackground(ApiConnector... params) {
//wird im Background Thread ausgeführt
return params[0].getValue();
}
#Override
protected void onPostExecute(String s) {
//wird im Mainthread ausgeführt
MainActivity.this.setText(s);
}
}
And I have a Class where i want to call the Webservice
public class ApiConnector
{
private static final String SOAP_ACTION ="urn:microsoft-dynamics-schemas/codeunit/AddService:Add";
private static final String METHOD_NAME ="Add";
private static final String NAMESPACE ="urn:microsoft-dynamics-schemas/codeunit/AddService";
private static final String URL ="http://192.168.0.154:9047/DynamicsNAV80/WS/CRONUS%20AG/Codeunit/AddService";
private static final String USERNAME="B.Denger";
private static final String PASSWORD ="TestPW123!";
public String getValue() {
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
request.addProperty("no","10");
PropertyInfo unamePI = new PropertyInfo();
PropertyInfo passPI = new PropertyInfo();
// Set Username
unamePI.setName("username");
// Set Value
unamePI.setValue(USERNAME);
// Set dataType
unamePI.setType(String.class);
// Add the property to request object
request.addProperty(unamePI);
//Set Password
passPI.setName("password");
//Set dataType
passPI.setValue(PASSWORD);
//Set dataType
passPI.setType(String.class);
//Add the property to request object
request.addProperty(passPI);
SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
soapEnvelope.setOutputSoapObject(request);
HttpTransportSE aht= new HttpTransportSE(URL);
try {
aht.call(SOAP_ACTION, soapEnvelope);
SoapPrimitive resultString = (SoapPrimitive) soapEnvelope.getResponse();
return resultString.toString();
}catch(Exception e ) {
e.printStackTrace();
return "Fail at Call";
}
}
}
I have set the using-permission in the Manifest file
<uses-permission android:name="android.permission.INTERNET"/>
in my MainActivity do i execute the AsynkTask with a Button
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
GetValueTask getValueTask = new GetValueTask();
getValueTask.execute(new ApiConnector());
}
});
after execution i get following Logcat entry:
W/System.err﹕ org.ksoap2.transport.HttpResponseException: HTTP request failed, HTTP status: 401
i googled a whole Day for it, but i did not solved the problem yet.
is there anybody who could help me, or could give me a hint where i have to search?
I found the solution here:
Android Consuming Dynamics NAV SOAP Web Service
but it didnt Work with the jcif 1.3.17 jar
at https://jcifs.samba.org/src/ can you download the latest version.
In my case I fixed same problem by adding this code:
List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
Complete task:
private class fnAsyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params)
{
//for linear parameter
SoapObject loRequest = new SoapObject(sNAMESPACE, sMETHOD_NAME);
// adding method property here serially
// loRequest.addProperty("CountryName", "france");
SoapSerializationEnvelope loEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
loEnvelope.implicitTypes = true;
loEnvelope.setOutputSoapObject(loRequest);
loEnvelope.dotNet = true;
HttpTransportSE loHttpTransport = new HttpTransportSE(_sURL);
loHttpTransport.debug = true;
try
{
List<HeaderProperty> llstHeadersProperty = new ArrayList<>();
llstHeadersProperty.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode("user:password".getBytes())));
loHttpTransport.call(sSOAP_ACTION, loEnvelope, llstHeadersProperty);
}
catch (HttpResponseException e)
{
// TODO Auto-generated catch block
Log.e("HTTPLOG", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("IOLOG", e.getMessage());
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
Log.e("XMLLOG", e.getMessage());
e.printStackTrace();
} //send request
Object result = null;
try {
result = (Object )loEnvelope.getResponse();
//See output in the console
Log.i("RESPONSE",String.valueOf(result));
} catch (SoapFault e) {
// TODO Auto-generated catch block
Log.e("SOAPLOG", e.getMessage());
e.printStackTrace();
}
return null;
}
}
Full example
http://www.nascenia.com/consuming-soap-web-services-from-android/

result of web service?

i wrote a code using SOAP function to get from web service , the problem is that the response is not an xml string , what i need to know , the error from my android code SOAP function ? or from web service ?
why the result is liske this
public String SOAP_ACTION2 = "http://tempuri.org/GetDataTable";
public String OPERATION_NAME2 = "GetDataTable";
public String SOAP_ADDRESS2 = "http://192.168.0.15/EServicedesk/DesktopModules/EServiceDesk.Website/ESDWebService/Auth.asmx?WSDL";
Object response;
String XMLData = null;
SoapSerializationEnvelope envelope;
SoapRequestTask2 task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
task = new SoapRequestTask2();
try {
XMLData = task.execute().get();
Log.i("task ", XMLData);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private class SoapRequestTask2 extends AsyncTask<Void, Void, String> {
// runs on ui thread.
private String data;
protected void onPreExecute() {
}
// runs in the background thread. do not update ui from here
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME2);
PropertyInfo pi = new PropertyInfo();
pi.setName("UserID");
pi.setValue(193);
pi.setType(Integer.class);
request.addProperty(pi);
envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
response = null;
try {
// httpTransport.debug=true;
httpTransport.call(SOAP_ACTION2, envelope);
// String ss = httpTransport.requestDump;
response = envelope.getResponse();
data = response.toString();
// Log.i("respons", envelope.getResponse().toString());
} catch (Exception exception) {
response = exception.toString();
XMLData = response.toString();
}
return data;
}
here is the result :
task 2: anyType{schema=anyType{element=anyType{complexType=anyType{choice=anyType{element=anyType{complexType=anyType{sequence=anyType{element=anyType{}; element=anyType{}; }; }; }; }; }; }; }; diffgram=anyType{DocumentElement=anyType{TargetTable=anyType{RequestHotList=MyRequests; Count=927; }; TargetTable=anyType{RequestHotList=MyAssignedRequests; Count=603; }; TargetTable=anyType{RequestHotList=MyServiceDeskRequests; Count=969; }; TargetTable=anyType{RequestHotList=MyWorkGroupRequests; Count=770; }; TargetTable=anyType{RequestHotList=MyApproval; Count=82; }; }; }; }
you can do something like this
Web service returns array of object
you can get value for each value for each object by going to perticular node then use getProperty() method to get value for required object as follow.
//old web services.
public void getLocation()
{
OPERATION_NAME = "GetLd";
SOAP_ACTION = Constants.strNAMESPACE+""+OPERATION_NAME;
REQUST_ID=3;
final Responce responce=new Responce();
Thread thread=new Thread(new Runnable()
{
SoapObject response;
#Override
public void run()
{
try
{
SoapObject request=new SoapObject(Constants.strNAMESPACE, OPERATION_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(Constants.strWEB_SERVICE_URL);
ht.call(SOAP_ACTION, envelope);
response = (SoapObject)envelope.bodyIn;
if(response!=null)
{
SoapObject str = null;
for(int i=0;i<response.getPropertyCount();i++)
str=(SoapObject) response.getProperty(i);
SoapObject str1 = (SoapObject) str.getProperty(0);
SoapObject str2 = null;
ArrayList<Location> arrData=new ArrayList<Location>();
for(int j=0;j<str1.getPropertyCount();j++)
{
str2 = (SoapObject) str1.getProperty(j);
Location location=new Location();
if(str2!=null)
{
responce.Result_Type=Constants.DataPresent;
if(isValidProperty(str2, "LocationName"))
{
location.setName(str2.getProperty("LocationName").toString());
}
if(isValidProperty(str2, "LocationId"))
{
location.setId(Integer.parseInt(str2.getProperty("LocationId").toString()));
}
arrData.add(location);
}
else
{
responce.Result_Type=Constants.NoDataPresent;
}
}
responce.ResponceData=arrData;
Log.d("Location", "------------------------");
for(int i=0;i<arrData.size();i++)
Log.d("Tag", arrData.get(i).toString());
}
}
catch (Exception e)
{
e.printStackTrace();
responce.Result_Type=Constants.Error;
}
finally
{
Message message=new Message();
message.what=REQUST_ID;
message.arg1=responce.Result_Type;
message.obj=responce;
handler.sendMessage(message);
}
}
});
thread.start();
}
boolean isValidProperty(SoapObject soapObject,String PropertyName)
{
if(soapObject!=null)
{
if(soapObject.hasProperty(PropertyName))
{
if(!soapObject.getProperty(PropertyName).toString().equalsIgnoreCase("")&&!soapObject.getProperty(PropertyName).toString().equalsIgnoreCase("anyType{}"))
return true;
else
return false;
}
return false;
}
else
return false;
}

Where Can I put IF statement for working?

I have some ksoap web service in timer action which is working every half an hour if I did it well. One of them send whole table rows to sql server and it turns me 0 or 1 depends on correctly sending. If it returns 1, it has to delete all row from sqlite.
Altough it returns 1, It does not get into if statements and does not work delete command.
I do not know my timer and thread is the right way for this and How can I do it correctly?
The Code:
try
{
final Timer V_Timer;
final Handler V_Handler;
V_Timer = new Timer();
V_Handler = new Handler(Looper.getMainLooper());
V_Timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
V_Handler.post(new Runnable()
{
public void run()
{
//for status update//
if(isConnected()){
Thread networkThread = new Thread() {
#Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_STATUS);
request.addProperty("MH_ID",hardwareID);
request.addProperty("Latitude",V_Latitude);
request.addProperty("Longitude",V_Longitude);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION_STATUS, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str_ = response.toString();
//final String str = response.toString()+"\n"+ V_Latitude +"\n"+V_Longitude;
runOnUiThread (new Runnable(){
public void run() {
Toast.makeText(MainActivity.this, str_, Toast.LENGTH_LONG).show();
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
//Insert Bulk//
if(isConnected()){
Thread networkThread2 = new Thread() {
#Override
public void run() {
str = "0";
try {
StringBuilder bulk = GetTotalRecord();
bulkinsert = bulk.toString();
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME_BULK);
request.addProperty("Insert_Bulk",bulkinsert);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION_BULK, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
str = response.toString();
runOnUiThread (new Runnable(){
public void run() {
// Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG).show();
/////delete sqlite table/////
Log.d("str", str);
if (str=="1")
{
try {
dbobject.delete(SQLiteDB.TABLE_NAME_S, null, null);
Toast.makeText(MainActivity.this, "All Answers sent", Toast.LENGTH_LONG).show() ;
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity.this, "Error: Answers could not send \n "+e.toString(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
finally{
sqlitedb.close();
}
}
/////delete sqlite table/////
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread2.start();
//Insert Bulk end//
}
}
}});
}
},10000, 1000*60*30);
}
catch(Exception ex)
{
}
if (str=="1")
you can not compare String object this way in Java.
You should use equalsTo() or convert str to int
for instance:
if (str.equalsTo("1")) {
}
or
int strInt = Integer.parseInt( str )
if (strInt == 1) {
}

Can't handle the thread in webservice method calling?

i have to write above code in my button click event. webservice working fine.webservice method return a String. thatString is equal to success go to next layout.it's working fine. but else part not working. toast make a exception
final SoapSerializationEnvelope envelope1 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope1.setOutputSoapObject(request1);
//msg.setText("hi");
envelope1.dotNet = true;
final Thread webser=new Thread(){
public void run()
{
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
System.out.println("four and Object value is : " +androidHttpTransport);
System.out.println("four and URL : " +URL);
//this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope1);
System.out.println("four a");
// Get the SoapResult from the envelope body.
SoapObject result1 = (SoapObject)envelope1.bodyIn;
if(result1 != null)
{
//Get the first property and change the label text
status=result1.getProperty(0).toString();
if(status.equalsIgnoreCase("success"))
{
Intent home=new Intent(LoginActivity.this,MainActivity.class);
startActivity(home);
}
else
{
Thread.sleep(1000);
Toast.makeText(LoginActivity.this,"Enter Valid Username/Password", Toast.LENGTH_LONG).show();
}
}
else
{
System.out.println("nodata");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception" +e);
}
}
};
webser.start();
}
});
You are accessing UI from back ground thread. To modife UI from Thread Use like this..
LoginActivity.this.runOnUiThread(new run Runnable() {
#Override
public void run() {
Toast.makeText(LoginActivity.this,"Enter Valid Username/Password", Toast.LENGTH_LONG).show();
}
});
And do not catch (Exception e). It is bad programming practice. :)

Toast is not displaying in catch block

Hi ! I'm trying to display a mesage when the network is off or the server is not responding. My messsage is visible in LOG but does not show on screen (is not toasted). I have a sample code which works fine but my code is not.
import android.view.View.OnKeyListener;
public class AgAppHelperMethods extends Activity {
private static final String LOG_TAG = null;
private static AgAppHelperMethods instance = null;
public static String varMobileNo;
public static String varPinNo;
String[][] xmlRespone = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agapphelpermethods);
}
protected AgAppHelperMethods() {}
public static AgAppHelperMethods getInstance()
{
if(instance == null)
{
instance = new AgAppHelperMethods();
}
return instance;
}
public static String getUrl ()
{
String url = "https://demo.accessgroup.mobi/";
return url;
}
public String[][] AgAppXMLParser(String parUrl)
{
String _node,_element;
String[][] xmlRespone = null;
try {
String url = AgAppHelperMethods.getUrl() + parUrl;
URL finalUrl = new URL(url);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(finalUrl.openStream()));
doc.getDocumentElement().normalize();
NodeList list=doc.getElementsByTagName("*");
_node=new String();
_element = new String();
xmlRespone = new String[list.getLength()][2];
for (int i=0;i<list.getLength();i++)
{
Node value=list.item(i). getChildNodes().item(0);
_node=list.item(i).getNodeName();
_element=value.getNodeValue();
xmlRespone[i][0] = _node;
xmlRespone[i][1] = _element;
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
}
}
How can I show my toast message on the screen? Thanks.
You can't do that. You can do something like this
boolean flag=true;//take globally
//working thread
.
.
.
catch (Exception e)
{
flag=false;
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
}
Once your working thread gets over check the flag value and show the Toast.
//Main Thread
if(!flag)
Toast.makeText(getApplicationContext(), "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
note: If you still want to show in NonUI Thread then you can use Handler or runOnUiThread()
Try this
Toast.makeText(AgAppHelperMethods.this, "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
Log.e(LOG_TAG, "CONNECTION ERROR FUNDAMO SERVER NOT RESPONDING", e);
make sure you pass right context, for example:
Toast.makeText(MyActivity.this , "error server not responding " + e.getMessage(),
Toast.LENGTH_SHORT).show();
I'm surprised this hasn't been answered yet. It appears to me all you need to do is run the Toast on the UI thread. Thus, in your catch block:
runOnUiThread(new Runnable(){
Toast.makeText(...);
});
Declare globally write it in oncreate and only show in catch block.
Toast toast;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
toast = Toast.makeText(ActivityDeliverables.this, "Server is not working, please contact with admin.", Toast.LENGTH_LONG);
}
try{
} catch (Exception e) {
toast.show();
}
This method is working for me if someone still need help:
getActivity().runOnUiThread(Runnable { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show() })
check this its working fine for me
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_finder);
show();
}
public void show()
{
try
{
throw new ArrayIndexOutOfBoundsException() ;
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "HI", Toast.LENGTH_LONG).show();
}
}
}

Categories

Resources