2017-02-25 10 views
-1

私は、Mysqlデータベースからデータを取得して表示するAsyncTaskを持っていますが、現在はうまくいきますが、単純なアダプタをカスタムアダプタに変更する必要があります。表示されます。しかし、自分のカスタムアダプタを自分のAsyncTaskで動作させるために何を変更する必要があるのか​​分かりません。AndroidスタジオAsyncTaskにカスタムアダプタを追加する

public class SearchFor extends AppCompatActivity implements View.OnClickListener { 

DBManager db; 
ListView lv; 

myAdapter myAdapter; 

// 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 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_search_for); 

    db = new DBManager(this); 

    // Hashmap for ListView 
    attractionList = new ArrayList<HashMap<String, String>>(); 
    transportList = new ArrayList<HashMap<String, String>>(); 
    lv = (ListView) findViewById(R.id.list_search); 
    this.registerForContextMenu(lv); 
} 


@Override 
public void onCreateContextMenu(ContextMenu menu, View v, 
           ContextMenu.ContextMenuInfo menuInfo) { 
    super.onCreateContextMenu(menu, v, menuInfo); 
    if(v.getId()== R.id.list_search){ 
     this.getMenuInflater().inflate(R.menu.context_menu_more,menu); 
    } 
} 

@Override 
public boolean onContextItemSelected(MenuItem item) { 
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); 
    switch (item.getItemId()) { 
     case R.id.menuBookmark: 
      testAdd(); 
      break; 
     case R.id.menuDirections: 
      break; 
     default: 
      return super.onContextItemSelected(item); 
    } 
    return false; 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.home_button, menu); 
    getMenuInflater().inflate(R.menu.optionsmenu,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.go_home){ 
     Intent i = new Intent(getApplicationContext(),QavelNav.class); 
     startActivity(i); 
    } 

    if (item.isChecked()) 
     item.setChecked(false); 
    else 
     item.setChecked(true); 

    if(id == R.id.attractionSub1){ 
     new LoadAllAttractions().execute(); 
    }else if(id == R.id.attractionSub2){ 
     Toast.makeText(getApplicationContext(),"Pubs", Toast.LENGTH_LONG).show(); 
    }else if(id == R.id.attractionSub3){ 

    }else if(id == R.id.attractionSub4){ 

    }else if(id == R.id.transportSub1){ 
     new LoadAllTransport().execute(); 
    }else if(id == R.id.transportSub2){ 

    } 
    return super.onOptionsItemSelected(item); 
} 

@Override 
public void onClick(View view) { 
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View viewClicked, 
           int position, long id) { 

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

/** 
* 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(SearchFor.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) { 
     final ArrayList<Adapter> listData = new ArrayList<Adapter>(); 
     listData.clear(); 
     // 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(
         SearchFor.this, attractionList, 
         R.layout.list_attractions, 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.tvAttractionName, R.id.tvAttractionType, R.id.tvAttractionLocation,R.id.tvAttractionOpening,R.id.tvAttractionClosing,R.id.tvAttractionNearbyStop1}); 
       // updating listview 

       //myAdapter = new myAdapter(listData); 
       lv.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(SearchFor.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(
         SearchFor.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.tvTransportName, R.id.tvTransportType, R.id.tvTransportLocation,R.id.tvTransportPhone}); 
       // updating listview 
       lv.setAdapter(adapter); 
      } 
     }); 

    } 

} 

public void testAdd(){ 
    TextView TextName = (TextView)findViewById(R.id.tvAttractionName); 
    System.out.println(TextName.getText().toString()); 
} 

public void addAttraction(View v){ 

    TextView TextName = (TextView)findViewById(R.id.tvAttractionName); 
    System.out.println(TextName.getText().toString()); 

    TextView TextType = (TextView) findViewById(R.id.tvAttractionType); 
    TextView TextLocation = (TextView)findViewById(R.id.tvAttractionLocation); 
    TextView TextOpening = (TextView)findViewById(R.id.tvAttractionOpening); 
    TextView TextClosing = (TextView)findViewById(R.id.tvAttractionClosing); 
    TextView TextNearbyStop = (TextView)findViewById(R.id.tvAttractionNearbyStop1); 

    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.tvTransportName); 
    TextView TextType = (TextView) findViewById(R.id.tvTransportType); 
    TextView TextLocation = (TextView)findViewById(R.id.tvTransportLocation); 
    TextView TextPhoneNumber = (TextView)findViewById(R.id.tvTransportPhone); 

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

class myAdapter extends BaseAdapter { 

    public ArrayList<Adapter> listItem; 

    public myAdapter(ArrayList<Adapter> listItem) { 
     this.listItem = listItem; 
    } 
    @Override 
    public int getCount() { 
     return listItem.size(); 
    } 
    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return position; 
    } 

    @Override 
    public View getView(int position, View view, ViewGroup viewGroup) { 
     LayoutInflater myInflator = getLayoutInflater(); 
     final View myView = myInflator.inflate(R.layout.list_attractions, null); 

     final Adapter ac = listItem.get(position); 

     TextView attractionId = (TextView) myView.findViewById(R.id.Attractionid); 
     attractionId.setText(ac.ID); 

     TextView Name = (TextView) myView.findViewById(R.id.tvAttractionName); 
     Name.setText(ac.Name); 

     TextView Type = (TextView) myView.findViewById(R.id.tvAttractionType); 
     Type.setText(ac.Type); 

     TextView Location = (TextView) myView.findViewById(R.id.tvAttractionLocation); 
     Location.setText(ac.Location); 

     TextView Opening = (TextView) myView.findViewById(R.id.tvAttractionOpening); 
     Opening.setText(ac.Opening); 

     TextView Closing = (TextView) myView.findViewById(R.id.tvAttractionClosing); 
     Closing.setText(ac.Closing); 

     TextView NearbyStop1 = (TextView) myView.findViewById(R.id.tvAttractionNearbyStop1); 
     NearbyStop1.setText(ac.NearbyStop); 

     return myView; 
    } 
} 
} 

興味のある部分は、下部にあるカスタムアダプタ(myAdapter)であり、最初のAsyncTaskは、カスタムアダプタに変換しようとするものであるイム。 onPostExecuteはシンプルなアダプタの場所で、カスタムアダプタを参照する必要があるかもしれませんが、これで助けが必要です。

答えて

0

両方のニーズに単一のアダプタを使用しているようです。

2つのAsyncTaskに2つのカスタムアダプタクラスを作成することについて考えましたか。

また、いくつかの提案: 1. DBフェッチのためにAsyncTaskを使用している場合、ローダーコールバックとカーソルローダーを使用できます。 2. preExecuteとpostExecuteはすでにUIスレッドで実行されています。したがって、runOnUIThreadを呼び出す必要はありません。 3.アダプターのgetViewメソッドでViewHolderパターンを使用すると、最適化が向上します。

+0

runOnUIThread呼び出しに関するヒントをありがとう、私はViewHolderパターンを見ていきますが、どのように私が持っているものでローダーコールバックを実装するのですか?つまり、それらを収容するためにreplace./changeが必要です。私はロードされた結果を私のカスタムアダプタにリンクします – Sam

関連する問題