In my app, I am calling a rest api command via an async task class I have made.
When I pass the string through the async task call like this
apiRequest = new APIRequest();
apiRequest.execute("https:api.my/api/url");
I get "Protocol not found: [Ljava.lang.String;#f51e848? ... ]" where the ... is the rest of my api call.
Inside my async class:
#Override
protected String doInBackground(String... str) {
try {
URL url = new URL(str + responseFormat + "&api_key=" + apiKey);
}
catch(Exception e) {
error = e.getMessage();
return null;
}
}
With this method, I get the error shown above. However, when I cut the string out of the apiRequest call, and paste it directly into the async task, it works perfectly.
Below, code is working with the cut and paste of the url.
apiRequest = new APIRequest();
apiRequest.execute();
Inside my async class:
#Override
protected String doInBackground(String... str) {
try {
URL url = new URL("https:api.my/api/url" + responseFormat + "&api_key=" + apiKey);
}
catch(Exception e) {
error = e.getMessage();
return null;
}
}
Related
I am trying to call another async task inside an OnPostExecute. The 2nd task does not run at all it seems. I am unable to print anything from within to the logs.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json = new JSONObject(result);
JSONArray lignes = json.getJSONArray("lignes");
populatelist(lignes);
}
catch (JSONException e) {
}
}
}
The populatelist function fills an array. Inside this function, I try to call the 2nd async task to get values based on this list.
protected void populatelist(JSONArray lignes){
try {
for(int i=0;i<lignes.length(); i++) {
JSONObject jsonas = lignes.getJSONObject(i);
String fdesignation = jsonas.getString("designation");
String fqtecde = jsonas.getString("qtecde");
String fcode_produit = jsonas.getString("code");
InfoStock(fcode_produit);
items.add(new PickingListProduitItem(fdesignation,"",fqtecde, ""));
}
}
catch(Exception e){
}
}
InfoStock() is the function that is used to return additional from a web service.
protected void InfoStock(String code_produit){
String stockURL = "http://" + mSharedPreferences.getString(Constants.SERVER_IP,"")+"//rest/v2/produit/info/code/"+ code_produit + "?stock=true";
try {
if (mDownloader != null && mDownloader.getStatus() == AsyncTask.Status.RUNNING) {
mDownloader.cancel(true);
mPDialog.dismiss();
}
mPDialog = new ProgressDialog(getApplicationContext());
mDownloader = new XMLDownloader(getApplicationContext(),mPDialog);
byte[][] downloadResults = mDownloader.execute(stockURL).get();
// Read stock info.
String s = new String(downloadResults[0], StandardCharsets.UTF_8);
JSONObject resp = new JSONObject(s);
PrixStockJSONParser psj = new PrixStockJSONParser(resp);
mRepInfoStock = psj.getRepInfoStock();
mRepInfoPrix = psj.getRepInfoPrix();
} catch (Exception ex) {
}
}
I am trying to set a value in the array <> created in the OnPostExecute Method. However there is no error message and the array is not populated at all. Even if I try to print a log from the InfoStock function, it does nothing.
Any suggestions are welcome.
I have this MainActivity which does two HTTP calls and return the JSON object back to the MainActivity class. I have seperately implemented the AsyncTask class and used the AsyncResponse interface to get the JSON object to the MainActivity by using the processFinish function call.
At first I came up with one HTTP call which worked perfectly.
Secondly I wanted to do another HTTP call in the same activity class. So I edit the code to cater the second HTTP call.
When I run the application, only the first HTTP call is working. When I call the second HTTP call it throws an exception saying reference to a null object
Then I checked by logging the onPostExecute method which calls the processFinish function. There I could see the JSON Object. So, that means the second JSON object doesn't get to the processFinish
How do I manage the second HTTP call? Please help me! I am new to Android.
Following is my AsyncTask class...
public class ServiceHandler extends AsyncTask<String, Void, JSONObject> {
String startStationID;
String endStationID;
String searchDate;
String startTime;
String endTime;
public ServiceHandler(String startStationID, String endStationID, String searchDate, String startTime, String endTime) {
this.startStationID = startStationID;
this.endStationID = endStationID;
this.searchDate = searchDate;
this.startTime = startTime;
this.endTime = endTime;
}
public interface AsyncResponse {
void processFinish(JSONObject output);
}
public AsyncResponse delegate=null;
public ServiceHandler(AsyncResponse delegate) {
this.delegate = delegate;
}
#Override
protected JSONObject doInBackground(String... params) {
String method = params[0];
JSONObject JSON_Object = null;
if (method.equals("getStations")) {
JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/station/getAll?lang=en");
} else if (method.equals("searchTrains")) {
JSON_Object = Constants.apiCall("http://api.lankagate.gov.lk:8280/railway/1.0/train/searchTrain?" +
"startStationID="+this.startStationID+"&" +
"endStationID="+this.endStationID+"&" +
"searchDate="+this.searchDate+"&" +
"startTime="+this.startTime+"&" +
"endTime="+this.endTime+"&" +
"lang=en");
}
return JSON_Object;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(JSONObject obj) {
try{
Log.d("onPostExecute",obj.toString());
delegate.processFinish(obj);
}catch (Exception e){
Log.e("onPostExecute",e.getMessage());
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
}
Following is my processFinish function...
#Override
public void processFinish(JSONObject output) {
Log.d("processFinish",output.toString());
if(!isSearchClicked) {
//Get all the stations...
if (output != null) {
Toast.makeText(MainActivity.this, "Successfully Connected!", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = output.getJSONObject("RESULTS");
output = null;
JSONArray dataArray = obj.getJSONArray("stationList");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject object1 = dataArray.getJSONObject(i);
String stationID = object1.getString("stationID");
String stationName = object1.getString("stationName");
stationNames.add(stationName);
stationIDs.add(stationID);
// stations.put(stationID,stationName);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
}
}else {
//search click action...
if (output != null) {
Toast.makeText(MainActivity.this, "Successfully Searched!", Toast.LENGTH_SHORT).show();
try {
JSONObject obj = output.getJSONObject("RESULTS");
JSONArray directTrains = obj.getJSONArray("directTrains");
// Log.d("array size",String.valueOf(directTrains.length()));
// for (int i = 0; i < directTrains.length(); i++) {
// JSONObject object1 = directTrains.getJSONObject(i);
//
// String stationID = object1.getString("stationID");
// String stationName = object1.getString("stationName");
// Log.d("JArr", stationID + " : " + stationName);
//
// stationNames.add(stationName);
// stationIDs.add(stationID);
//// stations.put(stationID,stationName);
// }
// Log.d("stationNames", stationNames.toString());
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, " Connection Failed!", Toast.LENGTH_SHORT).show();
Log.d("output",output.toString());
}
}
}
Following is my first HTTP call...
ServiceHandler sh = new ServiceHandler(this);
String method = "getStations";
sh.execute(method);
Following is my second HTTP call...
String method = "searchTrains"
ServiceHandler sh = new ServiceHandler(startStationID,endStationID,searchDate,startTime,endTime);
sh.execute(method);
Although I don't understand exactly what your problem is. There are few things I suggest you to do.
Here I go.
Don't use AsyncTask to make your http calls , use an intent services instead.
Use a OkHTTP library for your networking source
On your intent service send local broadcast with LocalBroadcastManager to broadcast your results from the http call.
Register broadcastsReceivers within your activities or fragments that will listen for those broadcasts that comes from the intent service
Why not to use AsyncTask: Because of configuration change - if you rotate your device you will lose that network calls-
Read about intent services here
I am trying to do a post to web api from android. The below is the code that I am using in android. The code is running without exception however the data is not inserted to the database. I included the code that I am using.
#Override
protected List doInBackground(Void... params)
{
List userDetails3 = new ArrayList();
URL url = null;
String urlshared = "http://10.0.0.9/MyWebApi/api/Student/PostAddStudent?userName="+"s4"+"&"+"password="+"1234"+"&"+"firsName="+"z"+"&"+"lastName="+"g"+"&"+"telephone="+"9160000000"+"&"+"address="+"2300 xxx"+"&"+"aliasMailId="+"s1.xx"+"&"+"emailId="+"xx#gmail.com"+"&"+"skypeId="+"z.g"+"";
try {
url = new URL(urlshared);
}
catch (MalformedURLException exception)
{
exception.printStackTrace();
}
HttpURLConnection httpURLConnection = null;
DataOutputStream dataOutputStream = null;
try
{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpURLConnection.setRequestMethod("POST");
PrintWriter out = new PrintWriter(httpURLConnection.getOutputStream()); // this code is executed without exception
}
catch (IOException exception)
{
exception.printStackTrace();
}
return userDetails3; // (in debug) the code will run successfuly till here without exception
}
I am trying to access the PostAddStudent in the webapi. The below is my implementation of the controller and I excluded the codes inside the methods. For your information, I did test "PostAddStudent" and the other methods in the RegisterController by using the postman and they are working fine and the data inserted to database.
public class RegisterController : ApiController
{
public IEnumerable<Register> GetRegisterAuth(string userName,string password)
{
//return instance of register
}
public IEnumerable<Register> GetRegisterByUserName(string userName)
{
//return instance of register
}
public HttpResponseMessage PostAddInstructor(string instUserName, string instPassword, string instFirsName, string instLastName, string instTelephone, string instAddress, string instAliasMailId, string instEmailId, string instSkypeId)
{
//add to database and if okay will return System.Net.HttpStatusCode.Created
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.Created, inst);
//if error exist then just return Badrequest
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.BadRequest, inst);
}
public HttpResponseMessage PostAddStudent(string userName, string password, string firsName, string lastName, string telephone, string address, string aliasMailId, string emailId, string skypeId)
{
//add to database and if okay will return System.Net.HttpStatusCode.Created
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.Created, inst);
//if error exist then just return Badrequest
var response = Request.CreateResponse<Instructor>(System.Net.HttpStatusCode.BadRequest, inst);
}
}
the below is the RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
//config.EnableSystemDiagnosticsTracing();
}
}
the below is the WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I need the android code that can do the post to PostAddStudent.
thanks
I want to execute java web service method from android app. My web service method signature looks like:
public String getData(String category) throws Exception
The method returns string and accepts a string as argument.
I have executed the method from google chrome's address bar as:
http://localhost:8080/JsonWebService/services/JsonWebService/getData?category=Marketing
Here getData is the name of the method and Marketing is the argument to that method. From explorer it works fine.
But when I add the same url to android app's httppost request it fails saying wrong number of arguments. My android app code is:
HttpPost post = new HttpPost("http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing");
HttpResponse httpres = httpClient.execute(post);
Please Note: Here 192.168.1.7 is required as I am executing the app directly on the device and hence I am not using localhost.
A non argument method executes correctly from android app also.
But when argument is inserted in the url why it fails saying wrong number of arguments in android app and how it executes correctly in google chrome on PC. Please help... Thanks...
I am adding the code here. My java web service code is as follows:
public class JsonWebService {
#POST
#Path("getData")
public String getData(String category) throws Exception {
JSONObject jsonData = new JSONObject();
String Email = "";
String Name = "";
String receivedCat = "";
boolean status = false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/admindb","root","");
java.sql.PreparedStatement query = con.prepareStatement("SELECT * FROM sample WHERE Category =" + "'" + category + "'" + ";");
ResultSet result = query.executeQuery();
while(result.next()){
receivedCat = result.getString("Category");
Name = result.getString("Name");
Email = result.getString("Email");
}
if(receivedCat.equals(category)){
status = true;
jsonData.put("Name",Name);
jsonData.put("Email", Email);
jsonData.put("status", status);
}
}
catch(Exception e) {
e.printStackTrace();
}
return jsonData.toString();
}
My android client code looks as follows:
btnCategory = (Button)findViewById(R.id.button1);
txtCategory = (EditText)findViewById(R.id.editText1);
gridV = (GridView)findViewById(R.id.gridView1);
txtName = (EditText)findViewById(R.id.editText3);
txtEmail = (EditText)findViewById(R.id.editText2);
btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread netThread = new Thread() {
public void run() {
try {
final JSONObject receivedJson;// = new JSONObject();
String URL = "http://192.168.1.7:8080/JsonWebService/services/JsonWebService/getData?category=Marketing?";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
receivedJson = new JSONObject(jsonPart);
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
txtName.setText(receivedJson.getString("Name"));
txtEmail.setText(receivedJson.getString("Email"));
}
catch(Exception e){
}
}
};
netThread.start();
}
});
}
The problem is in the java client in String URL, which is the string of URL that calls the java web service method. Please help me...
I unable to use put method to send data to particular link.. Please find below the code.Let me know if i have to make any change
public class test {
private static String url = "http://semldvw0728.google.net/.svc/web/testrequests/";
private static String urlconnection;
public static void main(String[] args) throws IOException {
StringBuffer xmlString = new StringBuffer();
xmlString.append("<TestRequest>");
xmlString.append("<DateRequested>2011-12-20</DateRequested>");
xmlString.append("<DemCapID>893467</DemCapID>");
xmlString.append("<DemCapVersion>1</DemCapVersion>");
xmlString.append("<IBIS_ID>13530</IBIS_ID>");
xmlString.append("<ProjectName>LTS</ProjectName>");
xmlString.append("<RequestedBy>ktmq331</RequestedBy>");
xmlString.append("<SampleNumber>SN1033645061</SampleNumber>");
xmlString.append("<Status>Sample Ordered</Status>");
xmlString.append("</TestRequest>");
System.out.println("xmlString :" + xmlString.toString());
url = url + 893467;
System.out.println("URL : " + url);
try {
System.out.println("URL : " + url);
HttpClient client = new HttpClient();
PutMethod putMethod = new PutMethod(url);
client.setConnectionTimeout(8000);
putMethod.setRequestBody(xmlString.toString());
System.out.println("statusLine>>>" + putMethod.getStatusLine());
System.out.println("statusLine>>>"+ putMethod.getResponseBodyAsString());
putMethod.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
I think you need to make a call to execute, or you could use the HttpClient object you've created to call this.
So maybe add this line after you're setting the request body for your putMethod...
client.executMethod(putMethod);