Chintan Soni
Chintan Soni

Reputation: 25267

error posting data to webservice

I want to post data using JSON. But i am not able to achieve this. This is my java code:

package com.bandapp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class UpcomingShow extends ListActivity {
    public static final String TAG_SHOW_TITLE = "show_title";
    public static final String TAG_SHOW_VENUE = "show_venue";
    public static final String TAG_SHOW_DATE = "show_date";
    public static final String TAG_SHOW_TIME = "show_time";
    public static String URL = "http://example.com/example/example/mainAPI.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.upcoming_show);
        new AsyncData().execute();
    }

    class AsyncData extends AsyncTask<String, Void, Void> {
        JSONParser jParser;
        ArrayList<HashMap<String, String>> upcomingShows;
        ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            pDialog = new ProgressDialog(UpcomingShow.this);
            pDialog.setTitle("Loading....");
            pDialog.setMessage("Please wait...");
            pDialog.show();
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(String... args) {
            // TODO Auto-generated method stub
            jParser = new JSONParser();
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            upcomingShows = new ArrayList<HashMap<String,String>>();
            params.add(new BasicNameValuePair("rquest", "={"));
            params.add(new BasicNameValuePair("method","band_info"));
            params.add(new BasicNameValuePair("body","[{}]}"));

            String res = "";
            try {
                HttpClient httpclient = new DefaultHttpClient(); 
                HttpPost httppost = new HttpPost(URL);
                httppost.setEntity(new UrlEncodedFormEntity(params));  
                HttpResponse response = httpclient.execute(httppost);  
                res = EntityUtils.toString(response.getEntity());
                JSONTokener t = new JSONTokener(res);
                JSONArray a = new JSONArray(t);
                JSONObject o = a.getJSONObject(0);
                String sc = o.getString(TAG_SHOW_TITLE);
                if(sc.equals("1"))
                {
                    // posted successfully
                    Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
                }
                else
                {
                 // error occurred
                    Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e) 
            {
                e.printStackTrace();
            }

            return null;
        }

        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (pDialog != null && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            ListAdapter adapter = new SimpleAdapter(UpcomingShow.this, upcomingShows, R.layout.upcomingshows_row, new String[] {
                    TAG_SHOW_TITLE, TAG_SHOW_DATE, TAG_SHOW_TIME, TAG_SHOW_VENUE }, new int[] { R.id.textTitle, R.id.textdate,
                    R.id.textTime, R.id.textVenue });
            setListAdapter(adapter);
        }
    }
}

Also i am not able to Toast any of the message that i have kept in doInBackground(). Can you please help me solving this please...

Upvotes: 0

Views: 134

Answers (4)

Android
Android

Reputation: 106

While doing AsyncTask<String, Void, Void> Task you can’t achieve Toast display in Main thread, user Log.d(“TAG”,”your-text”);

You can achieve Toast in onPostExecution()

}catch (Exception e) 
            {
                e.printStackTrace();
            }

            return sc;

}

protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (pDialog != null && pDialog.isShowing()) {
                pDialog.dismiss();
            }
         if(result.equals("1"))
            {
                // posted successfully
                Toast.makeText(UpcomingShow.this, result, Toast.LENGTH_SHORT).show();
            }
            else
            {
             // error occurred
                Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
            }
        }
    }

Upvotes: 1

jdnoprada
jdnoprada

Reputation: 33

I tried sending a post your request through Postman(google extension) and the URL you've provided responded with HTTP Status 200 but without a response message. Problem is, based on the code provided, is that you're expecting a message response from the said url. You should probably check with the server you are connecting with.

Upvotes: 1

VincentLamoute
VincentLamoute

Reputation: 810

You can't toast into doInBackground() because you can't update the UIview during the thread execution ! You should to use 'onProgress' and 'publishProgress'

change :

class AsyncData extends AsyncTask<String, Void, Void>

to:

class AsyncData extends AsyncTask<String, String, Void>

and override onProgress for toast:

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
        if (values[0] != null)
                Toast.makeText(UpcomingShow.this, values[0], Toast.LENGTH_SHORT).show();
}

And into doInBackground():

if(sc.equals("1"))
{
    publishProgress(sc);
   }
   else
   {
    publishProgress("Fail.");
 }

Upvotes: 1

dharmendra
dharmendra

Reputation: 7881

    if(sc.equals("1"))
                {
                    // posted successfully
                    Toast.makeText(UpcomingShow.this, sc, Toast.LENGTH_SHORT).show();
                }
                else
                {
                 // error occurred
                    Toast.makeText(UpcomingShow.this, "Fail.", Toast.LENGTH_SHORT).show();
                }

Remove this code form doInBackground

You can not update your UI on do in background , you can get result in onPostExecute and able to pop up those toast .

Upvotes: 1

Related Questions