错误将数据发布到webservice

时间:2013-04-24 09:57:17

标签: android json android-asynctask httpresponse

我想使用JSON发布数据。但我无法做到这一点。 这是我的java代码:

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);
        }
    }
}

此外,我无法Toast保存在doInBackground()中的任何消息。能帮助我解决这个问题吗...

4 个答案:

答案 0 :(得分:1)

    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();
                }
  

删除此代码表单doInBackground

您无法在后台更新您的用户界面,您可以在result中获得onPostExecute并能够弹出那些吐司。

答案 1 :(得分:1)

您无法向doInBackground()致敬,因为您无法在线程执行期间更新UIview!您应该使用'onProgress'和“publishProgress'

改变:

class AsyncData extends AsyncTask<String, Void, Void>

为:

class AsyncData extends AsyncTask<String, String, Void>

并覆盖forProgress 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();
}

进入doInBackground():

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

答案 2 :(得分:1)

执行AsyncTask<String, Void, Void>任务时,您无法在主线程,用户Log.d(“TAG”,“您的文本”)中实现Toast显示;

您可以在onPostExecution()

中实现Toast
}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();
            }
        }
    }

答案 3 :(得分:1)

我尝试通过Postman发送您的请求(Google扩展程序),并且您提供的网址已回复HTTP状态200,但没有回复消息。问题是,根据提供的代码,您希望来自所述URL的消息响应。您应该检查您正在连接的服务器。