将String传递给AsyncTask类

时间:2015-08-28 11:01:57

标签: java android android-asynctask

我有以下课程

public class Faculty extends Activity {

    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView listview;
    ListViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    static String NAME = "name";
    static String DESIGNATION = "designation";
    //static String POPULATION = "population";
    static String FAC_IMG = "fac_img";
    static String url;


    @Override
    public void onCreate(Bundle savedInstantState){
        super.onCreate(savedInstantState);
        // Get the view from listview_main.xml
        setContentView(R.layout.faculty_list);
        String data = getIntent().getStringExtra("Dpmt");
        if(data.equals("DOCScience")){
            url="Department%20Of%20Computer%20Science";
        }
        if(data.equals("DOIT")){
            url="Department%20Of%20Information%20%26%20Technology";
        }
        // Execute DownloadJSON AsyncTask
        new DownloadJSON().execute(url);

        //String url="http://192.168.170.89/bbau_faculty.php?dept="+Dept;
    }
    private class DownloadJSON extends AsyncTask<String, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(Faculty.this);
            // Set progressdialog title
            //mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(String... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            String url1=params[0];
            // Retrieve JSON Objects from the given URL address
            System.out.println(url1);
            jsonobject = JSONfunctions.getJSONfromURL("http://192.168.170.89/bbau_faculty.php?dept="+url1);

我正在调用DownloadJSON类 使用行

new DownloadJSON().execute(url);

在DownloadJSON类中的方法

doInBackground(String... params)我想收到execute(url)

中传递的网址
String url1=params[0];

但是url1打印为空。

3 个答案:

答案 0 :(得分:1)

  

但是url1打印为null。

你正在以正确的方式做事。如果您接收null作为值,则在您的情况下,这意味着

String data = getIntent().getStringExtra("Dpmt");

既不是DOCScience也不是DOITurl仍然使用默认值初始化(String为null,声明为类成员)

答案 1 :(得分:0)

可能是因为数据永远不等于DOCScience或DOIT。确保使用正确的密钥获取和设置数据。数据也可能是&#34;&#34;设置时。

答案 2 :(得分:0)

尝试检查url值,然后再将其传递给AsyncTask

if(url !=null && url.trim().length()>0){
  new DownloadJSON().execute(url);
}

如果检查数据值else-ifif

,也请使用DOCScience领导而不是多个DOIT
if(data.equals("DOCScience")){
   url="Department%20Of%20Computer%20Science";
}else if(data.equals("DOIT")){
   url="Department%20Of%20Information%20%26%20Technology";
}else{
  // no match
}