【问题标题】:Android studio retrieving position of item in listview through on clickAndroid Studio通过单击检索列表视图中项目的位置
【发布时间】:2017-02-18 20:20:39
【问题描述】:

我有一个 MYSQL 数据库,我从中检索信息并将其放入列表视图中。从这里我需要在单击带有书签的 sqlite 数据库时传输一些数据,但是当按下按钮时它不会返回正确的值,因为它会从可用选项中选择另一个值。我也尝试设置一个 setOnItemClickListener 但这似乎不起作用。如果有人可以帮助我使这些方法中的任何一种起作用,那就太好了。

所有景点类:

public class AllAttractions extends AppCompatActivity {

DBManager db;
ListView ls;

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> attractionList;
ArrayList<HashMap<String, String>> transportList;

// url to get all attraction list
private static String url_all_attractions = "http://10.0.2.2/TravelApp/get_all_attractions.php";
private static String url_all_transport = "http://10.0.2.2/TravelApp/get_all_transport.php";

// JSON Node names for attraction
private static final String TAG_SUCCESS = "success";
private static final String TAG_ATTRACTION = "attraction";
private static final String TAG_ATTRACTIONID = "Id";
private static final String TAG_NAME = "Name";
private static final String TAG_TYPE = "Type";
private static final String TAG_LOCATION = "Location";
private static final String TAG_OPENING = "OpeningTime";
private static final String TAG_CLOSING = "ClosingTime";
private static final String TAG_NEARBYSTOP = "NearbyStop";
private static final String TAG_LATITUDE = "Latitude";
private static final String TAG_LONGITUDE = "Longitude";

//JSON Node names for transport
private static final String TAG_TRANSPORT = "transport";
private static final String TAG_TRANSPORTID = "Id";
private static final String TAG_TIME = "Time";
private static final String TAG_NEXTSTOP = "NextStop";
private static final String TAG_PHONENUMBER = "PhoneNumber";

// attraction JSONArray
JSONArray attraction = null;
JSONArray transport = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_all_attractions);



    db = new DBManager(this);

    // Hashmap for ListView
    attractionList = new ArrayList<HashMap<String, String>>();

    transportList = new ArrayList<HashMap<String,String>>();

    // Get listview
    ls = (ListView) findViewById(R.id.list_search);


    ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
            // getting values from selected ListItem
            String Aid = ((TextView) view.findViewById(R.id.Attractionid)).getText()
                    .toString();

           System.out.println(Aid);
        }
    });


}



public void onAttraction(View v){
    // Loading attraction in Background Thread
    new LoadAllAttractions().execute();
}

public void onTransport(View v){
    // Loading transport in Background Thread
    new LoadAllTransport().execute();
}

/**
 * Background Async Task to Load all product by making HTTP Request
 */
class LoadAllAttractions extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllAttractions.this);
        pDialog.setMessage("Loading attractions. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    /**
     * getting All attraction from url
     */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_attractions, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Attractions: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // attraction found
                // Getting Array of Products
                attraction = json.getJSONArray(TAG_ATTRACTION);

                // looping through All Products
                for (int i = 0; i < attraction.length(); i++) {
                    JSONObject c = attraction.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ATTRACTIONID);
                    String name = c.getString(TAG_NAME);
                    String type = c.getString(TAG_TYPE);
                    String location = c.getString(TAG_LOCATION);
                    String opening = c.getString(TAG_OPENING);
                    String closing = c.getString(TAG_CLOSING);
                    String nearbyStop1 = c.getString(TAG_NEARBYSTOP);
                    String latitude = c.getString(TAG_LATITUDE);
                    String longitude = c.getString(TAG_LONGITUDE);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ATTRACTIONID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_TYPE, type);
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_OPENING,opening);
                    map.put(TAG_CLOSING,closing);
                    map.put(TAG_NEARBYSTOP, nearbyStop1);
                    map.put(TAG_LATITUDE, latitude);
                    map.put(TAG_LONGITUDE, longitude);



                    // adding HashList to ArrayList
                    attractionList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all attraction
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllAttractions.this, attractionList,
                        R.layout.list_attraction, new String[]{TAG_ATTRACTIONID,
                        TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_OPENING,TAG_CLOSING,TAG_NEARBYSTOP,TAG_LATITUDE,TAG_LONGITUDE},
                        new int[]{R.id.Attractionid, R.id.name, R.id.type, R.id.location,R.id.open,R.id.close,R.id.nearbystop, R.id.tvLat,R.id.tvLon});
                // updating listview
                ls.setAdapter(adapter);
            }
        });

    }

}

class LoadAllTransport extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllAttractions.this);
        pDialog.setMessage("Loading Transport. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();

    }

    /**
     * getting All attraction from url
     */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_transport, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Transport: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // attraction found
                // Getting Array of Products
                transport = json.getJSONArray(TAG_TRANSPORT);

                // looping through All Products
                for (int i = 0; i < transport.length(); i++) {
                    JSONObject c = transport.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_TRANSPORTID);
                    String name = c.getString(TAG_NAME);
                    String type = c.getString(TAG_TYPE);
                    String location = c.getString(TAG_LOCATION);
                    String time = c.getString(TAG_TIME);
                    String nextStop = c.getString(TAG_NEXTSTOP);
                    String phoneNumber = c.getString(TAG_PHONENUMBER);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_TRANSPORTID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_TYPE, type);
                    map.put(TAG_LOCATION, location);
                    map.put(TAG_TIME,time);
                    map.put(TAG_NEXTSTOP,nextStop);
                    map.put(TAG_PHONENUMBER, phoneNumber);

                    // adding HashList to ArrayList
                    transportList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all attraction
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllAttractions.this, transportList,
                        R.layout.list_transport, new String[]{TAG_TRANSPORTID,
                        TAG_NAME,TAG_TYPE,TAG_LOCATION,TAG_TIME,TAG_NEXTSTOP,TAG_PHONENUMBER},
                        new int[]{R.id.transportid, R.id.TransportName, R.id.TransportType, R.id.TransportLocation,R.id.TransportTime,R.id.TransportNextStop,R.id.TransportPhoneNumber});
                // updating listview
                ls.setAdapter(adapter);
            }
        });

    }

}

public void addBookmark(View v){
    TextView TextName = (TextView)findViewById(R.id.name);
    System.out.println(TextName.getText().toString());
    TextView TextType = (TextView) findViewById(R.id.type);
    TextView TextLocation = (TextView)findViewById(R.id.location);
    TextView TextOpening = (TextView)findViewById(R.id.open);
    TextView TextClosing = (TextView)findViewById(R.id.close);
    TextView TextNearbyStop = (TextView)findViewById(R.id.nearbystop);

    ContentValues values = new ContentValues();
    values.put(DBManager.ColName,TextName.getText().toString());
    values.put(DBManager.ColType,TextType.getText().toString());
    values.put(DBManager.ColLocation,TextLocation.getText().toString());
    values.put(DBManager.ColOpening,TextOpening.getText().toString());
    values.put(DBManager.ColClosing,TextClosing.getText().toString());
    values.put(DBManager.ColNearbyStop,TextNearbyStop.getText().toString());

    long id = db.Insert("BookmarkAttraction",values);
    if (id > 0)
        Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}

public void addTransport(View v){
    TextView TextName = (TextView)findViewById(R.id.TransportName);
    TextView TextType = (TextView) findViewById(R.id.TransportType);
    TextView TextLocation = (TextView)findViewById(R.id.TransportLocation);
    TextView TextTime = (TextView)findViewById(R.id.TransportTime);
    TextView TextNextStop = (TextView)findViewById(R.id.TransportNextStop);
    TextView TextPhoneNumber = (TextView)findViewById(R.id.TransportPhoneNumber);

    ContentValues values = new ContentValues();
    values.put(DBManager.ColName,TextName.getText().toString());
    values.put(DBManager.ColType,TextType.getText().toString());
    values.put(DBManager.ColLocation,TextLocation.getText().toString());
    values.put(DBManager.ColTime,TextTime.getText().toString());
    values.put(DBManager.ColNextStop,TextNextStop.getText().toString());
    values.put(DBManager.ColPhoneNumber,TextPhoneNumber.getText().toString());

    long id = db.Insert("BookmarkTransport",values);
    if (id > 0)
        Toast.makeText(getApplicationContext(),"Added to bookmarks", Toast.LENGTH_LONG).show();
    else
        Toast.makeText(getApplicationContext(),"cannot insert", Toast.LENGTH_LONG).show();
}

public void goDirect(View v){

  TextView Latit = (TextView)findViewById(R.id.tvLat);
  TextView Longit = (TextView)findViewById(R.id.tvLon);

    Intent passData = new Intent(getApplicationContext(), MapPath.class);

    passData.putExtra("Latitude",Latit.getText().toString());
    passData.putExtra("Longitude",Longit.getText().toString());

    startActivity(passData);
}
}

DBManager 类:

public class DBManager  {


private SQLiteDatabase sqlDB;
  static final String ColId = "ID";
  static final String DBName = "InternalDB";
  static final String TableName = "BookmarkAttraction";
  static final String TableName2 = "BookmarkTransport";
  static final String TableName3 = "Itinerary";
  static final String ColItineraryName = "ItineraryName";
  static final String ColDate = "Date";
  static final String ColType = "Type";
  static final String ColName = "Name";
  static final String ColLocation = "Location";
  static final String ColOpening = "OpeningTime";
  static final String ColClosing = "ClosingTime";
  static final String ColNearbyStop = "NerbyStop1";
  static final String ColTime = "Time";
  static final String ColNextStop = "NextStop";
  static final String ColPhoneNumber = "PhoneNumber";

  static final int DBVersion = 1;

  static final String CreateTable = "CREATE TABLE IF NOT EXISTS " + TableName + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColType+ " TEXT," +
        ColName+ " TEXT," + ColLocation+ " TEXT," + ColOpening+ " TEXT," +ColClosing+ " TEXT," + ColNearbyStop+ " TEXT);";

  static  final String CreateTabe2 = "CREATE TABLE IF NOT EXISTS " +TableName2 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,"
        + ColType + " TEXT,"
        + ColName + " TEXT,"
        + ColLocation + " TEXT,"
        + ColTime+ " TEXT,"
        + ColNextStop + " TEXT,"
        + ColPhoneNumber + " TEXT);";

  static final String CreateTable3 = "CREATE TABLE IF NOT EXISTS " + TableName3 + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + ColItineraryName + " TEXT,"
        + ColDate + " TEXT," + ColName + " TEXT," + ColLocation + " TEXT," + ColTime + " TEXT);";


  static class DBHelper extends SQLiteOpenHelper{
    Context context;

    DBHelper(Context context){
        super(context, DBName, null, DBVersion);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Toast.makeText(context,DBName,Toast.LENGTH_LONG).show();
        db.execSQL(CreateTable);
        Toast.makeText(context,"Attraction is created ", Toast.LENGTH_LONG).show();
        db.execSQL(CreateTabe2);
        Toast.makeText(context,"Transport table created", Toast.LENGTH_LONG).show();
        db.execSQL(CreateTable3);
        Toast.makeText(context,"Itinerary table created", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("DROP TABLE IF EXISTS" + TableName);
        db.execSQL("DROP TABLE IF EXISTS" + TableName2);
        db.execSQL("DROP TABLE IF EXISTS" + TableName3);
            onCreate(db);
    }
}


public DBManager(Context context){
    DBHelper db = new DBHelper(context);
    sqlDB = db.getWritableDatabase();
}

public long Insert(String tablename,ContentValues values){
    long ID =  sqlDB.insert(tablename,"",values);
    return ID;
}

public Cursor Query(String tablename, String [] projection, String selection, String [] selectionArgs, String sortOrder){
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(tablename);

    Cursor cursor = qb.query(sqlDB,projection, selection, selectionArgs,null,null,sortOrder);
    return cursor;
}

public int Delete(String tablename,String selection, String[] selectionArgs){
    int count = sqlDB.delete(tablename,selection,selectionArgs);
    return count;
}
}

发送数据的按钮位于 AllAttractions 的第 367 行,如果有人可以解决我尝试过的问题或提出更好的方法,将不胜感激。

【问题讨论】:

  • 问题是什么?什么是第 367 行?我们这样做是免费的,你知道吗?
  • 问题是我试图从列表项中获取数据并将其放入 sqlite 数据库,但在按下添加按钮时无法获取正确的数据,第 367 行是数据所在的位置检索/转移
  • 山姆,我们无法知道 367 是哪一行
  • public void addTransport(View v){...,链接到检索/传输数据的按钮的方法
  • 风格变化,为清晰起见简化解释。

标签: java android mysql sqlite listview


【解决方案1】:

试试这个ClickListener

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // getting values from selected ListItem
        HashMap<String, String> item = attractionList.get(position);
        Log.d("AllAttractions", "clicked id = " + item.get(TAG_ATTRACTIONID));
        Log.d("AllAttractions", "clicked name = " + item.get(TAG_NAME));
    }

【讨论】:

  • 我假设我把它放到了我班级的 onCreate 中,但这似乎不起作用,因为当我点击一个列表项时它没有注册/点击它们,所以不输出任何东西
  • 这不适用于onCreate。只需将其复制/粘贴到您的代码中并将ListView 的侦听器设置为this。确保你的班级当然实现了Listener
  • 我将侦听器添加到我的类并将列表视图更改为此,并移动了您的代码,但@Override 有一个错误,指出它没有覆盖其超类中的方法
猜你喜欢
  • 2019-01-15
  • 2019-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-15
  • 2015-11-17
  • 2019-11-01
  • 1970-01-01
相关资源
最近更新 更多