2017-02-18 68 views
-1

我有一個MYSQL數據庫,我從中檢索信息和放置到一個列表視圖。從這裏我需要傳遞一些數據,當點擊到書籤的sqlite數據庫,但是當按下按鈕時,它不會返回正確的值,因爲它從可用選項中選擇另一個。我也嘗試設置setOnItemClickListener,但這似乎不起作用。如果有人能幫助我使用這兩種方法中的任何一種,那就太棒了。Android工作室通過點擊檢索項目在ListView的位置通過點擊

AllAttractions類:

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線,如果有人能解決什麼我已經嘗試過或建議一個按鈕更好的方式,將不勝感激。

+0

問題是什麼?什麼是367線?我們這樣做是免費的,你知道嗎? – JonZarate

+0

問題是即時通訊嘗試從列表項中獲取數據並將其放入sqlite數據庫中,但在按下添加按鈕時未能獲取正確的數據,第367行是檢索/傳輸數據的位置 – Sam

+0

Sam,there是沒有辦法讓我們知道什麼是行367 – JonZarate

回答

0

試試這個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)); 
    } 
+0

我假設我把這到我的班的onCreate,但這似乎並沒有工作,因爲當我點擊一個列表項目,它不註冊/點擊它們,所以不輸出任何東西 – Sam

+0

這不是'onCreate'。只需將它複製/粘貼到代碼中,並將「ListView」的偵聽器設置爲「this」。確保你的類當然實現了'Listener'。 – JonZarate

+0

我將偵聽器添加到我的類中,並將listview更改爲此,並移動了您的代碼,但@Override有一個錯誤,表示它沒有從其超類中重寫方法 – Sam