Android,从MySQL读取数据后,listview在屏幕显示关闭后填充

时间:2017-04-16 12:01:57

标签: android mysql listview android-asynctask

我正在尝试从MySQL数据库中获取数据并将其显示在listview中。成功检索数据,但在屏幕显示关闭之前不会填充列表视图。在填充列表视图之前,进度对话框也不会出现。有什么建议?

public class BestLinksActivity extends AppCompatActivity {

public ListView myListView;
public MyListViewAdapter mAdapter;
public List<HotelInfo> dataSource;
private String cityName;
ProgressDialog mProgressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_best_links);
    dataSource = new ArrayList<>();

    mProgressDialog = new ProgressDialog(BestLinksActivity.this);
    mProgressDialog.setMessage("Loading data...");

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        cityName = extras.getString("City");
    }

    DataBaseReader dbReader = new DataBaseReader();
    if (!(cityName.equals(null))) {
        dbReader.execute(cityName);
    } else {
        Toast.makeText(getApplicationContext(), "City name not specified", Toast.LENGTH_SHORT).show();
    }

    //Create adapter
    mAdapter = new MyListViewAdapter(getApplicationContext(), dataSource);
    //Configure the listview
    myListView = (ListView) findViewById(R.id.main_list_view);
    myListView.setAdapter(mAdapter);
    myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

            // ListView Clicked item value
            HotelInfo currentItem = dataSource.get(position);

            //Open url of the currentItem in web browser
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(currentItem.getLinkUrl())));
        }
    });
}

public String getTitle(String url) {
    String[] subStrings = url.split("/");
    String urlTitle = "";
    for (int i = 0; i < subStrings.length; i++) {
        if (subStrings[i].equals("t"))
            urlTitle = (subStrings[i + 1]);

    }
    urlTitle = urlTitle.replace("-", " ");
    urlTitle=((urlTitle.charAt(0)+"").toUpperCase()).concat(urlTitle.substring(1));
    return urlTitle;
}

public class DataBaseReader extends AsyncTask<String, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.show();
    }


    @Override
    protected String doInBackground(String... params) {

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(15, TimeUnit.SECONDS)
                .readTimeout(15, TimeUnit.SECONDS)
                .build();

        Log.d("CheckParam", params[0]);
        RequestBody postBody = new FormBody.Builder()
                .add("cityName", params[0])
                .build();

        Request myRequest = new Request.Builder()
                .url("http://172.18.0.32/extractData.php")
                .post(postBody)
                .build();

        String serverResponse = null;
        try {
            Response response = okHttpClient.newCall(myRequest).execute();
            serverResponse = response.body().string();
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            JSONObject myJsonObj = new JSONObject(serverResponse);
            JSONArray myJsonArray = myJsonObj.getJSONArray("server_response");
            for (int index = 0; index < myJsonArray.length(); index++) {
                JSONObject linkObject = myJsonArray.getJSONObject(index); //Otherwise, you will get last element
                HotelInfo myHotelInfo = new HotelInfo();
                myHotelInfo.setLinkUrl(linkObject.getString("Link"));
                myHotelInfo.setLinkTitle(getTitle(myHotelInfo.getLinkUrl()));
                dataSource.add(myHotelInfo);
            }


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

        Log.d("MyKeyser", serverResponse);
        return serverResponse;
    }


    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.d("MyKey", s);
        if (mProgressDialog!=null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }

    }
}

}

1 个答案:

答案 0 :(得分:1)

将以下行添加到onPostExecute

mAdapter.notifyDataSetChanged();

您需要通知适配器数据已更改。 请参阅the docs

关于ProgressBar,您需要将其放在activity_best_links布局的某些布局下。 最好的方法是不以编程方式创建它,而是将其添加到xml布局文件中,参见示例here,然后通过mProgress.setVisibility();

播放其可见性