【问题标题】:Populating Listview from database when item selected in a spinner then button clicked当在微调器中选择项目然后单击按钮时,从数据库中填充 Listview
【发布时间】:2015-07-30 23:21:16
【问题描述】:

好的,所以我正在创建一个将使用当前 gps 位置(纬度/经度)的应用程序。用户必须从Spinner 中选择一个指定的半径(0.5-100 英里)。然后,当单击时,将有一个Button (onClickListener()) 将位置从 SQLite 数据库中的设置半径填充到ListView。从那里,从 ListView 中选择一个将调用 Activity (Intent) 的项目。

我有 ListView 填充数据库中的数据,但我遇到了从 onClick 事件 (Button) 填充它的问题。此外,如果有人能弄清楚如何获取当前位置以根据设置的半径(来自Spinner)比较数据库中列出的位置,并在ListView 中显示匹配的位置,我将不胜感激那。 谢谢!

SN:我让它显示当前位置。这是我的代码。

Java 文件

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class MetersActivity extends ActionBarActivity {

private Toolbar toolbar;
private DrawerLayout drawerLayout;

private static Button search;
private TextView myAddress;
GPSTracker gps;

//new instance of db from meter info database
MeterInfoDatabase myDb;
private Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
final MeterInfoDatabase db = new MeterInfoDatabase(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_meters);

    //myDb = new MeterInfoDatabase(this);
   final ListView listView = (ListView) findViewById(R.id.MeterList);
    Log.d("LOG", "Before testing the database");
    /*
    Testing Database Part
     */

    List<MeterInfoSQL> allMeters = db.getAllMeters();
    ArrayList<String> ar = new ArrayList<String>();
    for(MeterInfoSQL m : allMeters)
    {
        //Toast.makeText(getApplicationContext(), m.getMeterNumber() + "  Saved", Toast.LENGTH_LONG).show();
        String str = "Meter #: " + m.getMeterNumber();
        ar.add(str);
    }

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar);
    listView.setAdapter(adapter);

    toolbar= (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    myAddress = (TextView) findViewById(R.id.myaddress);

    //search button click
    onClickButtonListener();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_meters, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

//Used to get location via GPS when search button is tapped
public void onClickButtonListener() {

    final Context context = this;

    search = (Button) findViewById(R.id.MeterSearch_button);

    search.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            gps = new GPSTracker(MetersActivity.this);

            //gps coordinates
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            if (gps.canGetLocation()) {

                //Shows address
                try {
                    List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);

                    if(addresses != null) {
                        Address returnedAddress = addresses.get(0);
                        StringBuilder strReturnedAddress = new StringBuilder("Your Current Address:\n");
                        for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
                            strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                        }
                        myAddress.setText(strReturnedAddress.toString());

                    } else{
                        myAddress.setText("No Address returned!");
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    myAddress.setText("Canont get Address!");
                }

            }
            else {
                gps.showSettingsAlert();

            }
         //want the lisview to populate when this button is clicked
         /*when i move it here I get an error at "this"
          ArrayAdapter<String> adapter = new ArrayAdapter<String>
         //---> here (this, android.R.layout.simple_list_item_1, ar);
          listView.setAdapter(adapter); */

        }
    });
}
}

XML 布局

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/background"
tools:context="com.example.ataccofficial.MetersActivity">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ff8a8a90"
    android:clickable="true"
    tools:context="com.example.themetest.MetersActivity">

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />

    <TextView
        android:id="@+id/meterSelectRadiusText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/app_bar"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:inputType="none"
        android:text="Select Radius:"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#ffffffff"
        android:textSize="25dp" />

    <Spinner
        android:id="@+id/meter_spinner"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/textView"
        android:layout_below="@+id/meterSelectRadiusText"
        android:layout_marginRight="10dp"
        android:entries="@array/meter_array"
        android:gravity="center"
        android:spinnerMode="dialog"
        android:textColor="#ffffffff" />


    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/meter_spinner"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="27dp"
        android:background="#ff8a8a90"
        android:text="Location:"
        android:textColor="#ffffffff"
        android:textSize="15sp" />

    <TextView
        android:id="@+id/myaddress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:autoText="false"
        android:editable="false"
        android:enabled="false"
        android:focusable="true"
        android:textColor="@color/primaryColor"
        android:textSize="15sp" />

    <Button
        android:id="@+id/MeterSearch_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:onClick="Search"
        android:text="Search"
        android:textSize="25dp"
        android:typeface="normal"
        android:textStyle="bold"
        android:layout_below="@+id/myaddress"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Customer"
        android:id="@+id/lablecrm"
        android:layout_alignBottom="@+id/dailyReportDivider"
        android:layout_alignParentStart="true"
        android:textColor="#ffffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Issue"
        android:id="@+id/lableIssue"
        android:layout_alignBottom="@+id/dailyReportDivider"
        android:layout_centerHorizontal="true"
        android:textColor="#ffffffff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Distance"
        android:id="@+id/lableDistance"
        android:layout_alignBottom="@+id/dailyReportDivider"
        android:layout_alignParentEnd="true"
        android:textColor="#ffffffff" />

    <View
        android:id="@+id/dailyReportDivider"
        android:layout_width="fill_parent"
        android:layout_height="2dp"
        android:background="@android:color/darker_gray"
        android:layout_below="@+id/myaddress"
        android:layout_alignParentStart="true"
        android:layout_marginTop="84dp" />

    <ListView
        android:id="@+id/MeterList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dailyReportDivider"
        android:layout_centerHorizontal="true"
        android:choiceMode="singleChoice"
        android:textColor="#ffffffff"/>


</RelativeLayout>
<fragment
               android:id="@+id/fragment_navigation_drawer"
                    android:name="com.example.ataccofficial.NavigationDrawerFragment"
               android:layout_width="250dp"
               android:layout_height="match_parent"
               android:layout_gravity="start"
               android:layout="@layout/fragment_navigation_drawer"
               tools:layout="@layout/fragment_navigation_drawer" />

</android.support.v4.widget.DrawerLayout>

微调器字符串

<string-array name="meter_array">
    <item>.5 Miles</item>
    <item>1 Miles</item>
    <item>5 Miles</item>
    <item>10 Miles</item>
    <item>15 Miles</item>
    <item>20 Miles</item>
    <item>25 Miles</item>
    <item>50 Miles</item>
    <item>100 Miles</item>
</string-array>

【问题讨论】:

  • 我已经在这工作了大约 2 周了,但仍然没有任何进展。
  • 尝试使用button.setOnClicListener.....
  • 但是最好的方式是在你的activity中实现接口OnclickListener,我认为是...... yourActivity extends Activity实现了OnClickListener,这是最好的方式
  • 谢谢。我会测试一下并告诉你。

标签: java android sqlite listview spinner


【解决方案1】:

在按钮侦听器之外创建了一个方法,用于填充 listview,并在侦听器内部调用它。

//Used to get location via GPS when search button is tapped
public void onClickButtonListener() {

    final Context context = this;

    search.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            gps = new GPSTracker(MetersActivity.this);

            //gps coordinates
            double latitude = gps.getLatitude();
            double longitude = gps.getLongitude();

            if (gps.canGetLocation()) {

                //Shows address
                try {
                    List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);

                    if (addresses != null) {
                        Address returnedAddress = addresses.get(0);
                        StringBuilder strReturnedAddress = new StringBuilder("Your Current Address:\n");
                        for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                            strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                        }
                        myAddress.setText(strReturnedAddress.toString());

                    } else {
                        myAddress.setText("No Address returned!");
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    myAddress.setText("Canont get Address!");
                }

            } else {
                gps.showSettingsAlert();

            }
          process_data();

        }
    });

}


  private void process_data(){

  List<MeterInfoSQL> allMeters = db.getAllMeters();
  ar = new ArrayList<String>();
  for(MeterInfoSQL m : allMeters)
  {
      //Toast.makeText(getApplicationContext(), m.getMeterNumber() + "   Saved", Toast.LENGTH_LONG).show();
      String str = "Meter #: " + m.getMeterNumber() + " Contact " + m.getAccountNumber();
      ar.add(str);
  }

  adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar);
  listView.setAdapter(adapter);
  doPopulate();

}

   private void doPopulate() {
    adapter.notifyDataSetChanged();
}

【讨论】:

  • 现在我正在从微调器填充列表视图。
【解决方案2】:

创建另一种方法来处理您的任务。在您的onClick() 中,this 语句不引用Activity,这就是它抛出错误的原因。

首先,尝试将您的ArrayAdapterListViewArrayList&lt;String&gt; 声明为全局变量。这可以让您的工作更轻松。

private ArrayAdapter <String> adapter;
private ListView listView;
private ArrayList<String> ar = new ArrayList<String>();

然后,在您的 onCreate() 方法上更改行

final ListView listView = (ListView) findViewById(R.id.MeterList);
// ...
ArrayList<String> ar = new ArrayList<String>();
// ...
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar);

listView = (ListView) findViewById(R.id.MeterList);
// ...
ar = new ArrayList<String>();
// ...
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, ar);

稍后在您的onClickListener()

search.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {

        // Your code.

        // Change your "ar" Array here, and later call the following method.
        doPopulate();
    }});

private void doPopulate() {
    adapter.notifyDataSetChanged();       
}

我想您可以简单地从onClick() 中调用notifyDataSetChanged(),但我现在无法测试此代码。稍后告诉我它是否有效。

您可以阅读有关此here 的更多信息。

【讨论】:

  • 我创建了一个方法并在 'onClick' 监听器中调用它
  • 它的做法有点不同。我仍然按照您的方式收到错误。我确实在全局范围内声明了变量,这也有帮助。
  • 我已经回答了,但我还不能接受,我还是新手 :)。我现在只是想弄清楚剩下的部分
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多