Android,从 MySQL 读取数据后,屏幕显示关闭后填充列表视图

Posted

技术标签:

【中文标题】Android,从 MySQL 读取数据后,屏幕显示关闭后填充列表视图【英文标题】:Android, after reading data from MySQL, listview populates after screen display is off 【发布时间】:2017-09-12 05:12:34 【问题描述】:

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

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

    



【问题讨论】:

由于您的数据源列表已更新,您必须通过调用 notifyDatasetChanged() 通知适配器所述更改。 【参考方案1】:

将以下行添加到您的onPostExecute

mAdapter.notifyDataSetChanged();

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

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

【讨论】:

很高兴我能提供帮助,请将答案标记为已接受,以便从未回答的队列中删除此问题并帮助其他人。 完成。还有一个问题,如果服务器离线或没有响应,我如何显示 Toast? 添加到您的 onPostExecute:if (s == null) Toast.makeText(BestLinksActivity.this, "Hello", Toast.LENGTH_SHORT).show()

以上是关于Android,从 MySQL 读取数据后,屏幕显示关闭后填充列表视图的主要内容,如果未能解决你的问题,请参考以下文章

Android Auto - 如何显式打开谷歌地图进行导航以显示在汽车屏幕上(intent.setPackage 不起作用)

PHP - 访问 MS SQL 视图和回显结果

Android触控事件处理机制(基于Android 11)

硬解直显模式实现抓图功能

硬解直显模式实现抓图功能

硬解直显模式实现抓图功能