saved arrayList<HashMap<String,String>,displaying them without Internet - android

I have arrayList> in my app.I have this array fro, the Internet,through parsing json data. I want to save this array,then my app can be work without Internet.What can I do? I know how to stored data im SQLite,but response of query is cursor,I know that I can create custom adapter that working with cursor.But maybe I can find easier way for this?
MainActivity:
public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
Intent intent;
private static String url = "https://fierce-citadel-4259.herokuapp.com/hamsters";
private static final String TITLE = "title";
private static final String DESCRIPTION = "description";
private static final String IMAGE = "image";
ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(MainActivity.this).execute();
lv=(ListView) findViewById(android.R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String title1 = jsonlist.get(position).get("title");
String description1 = jsonlist.get(position).get("description");
String url1 = jsonlist.get(position).get("image");
intent = new Intent(MainActivity.this, DetailInfo.class);
intent.putExtra("title", title1);
intent.putExtra("description", description1);
intent.putExtra("url", url1);
startActivity(intent);
dbHelper = new SqlHelper(MainActivity.this);
try {
dbHelper.open();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
}
#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_main, 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.reload) {
new ProgressTask(MainActivity.this).execute();
}
else if(id == R.id.menu_item_share){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Put whatever you want");
startActivity(Intent.createChooser(intent,"Share via"));
}
return super.onOptionsItemSelected(item);
}
private class ProgressTask extends AsyncTask<String,Void,Boolean> {
private ProgressDialog dialog;
private ListActivity activity;
private Context context;
public ProgressTask(MainActivity activity) {
this.activity = activity;
context = activity;
dialog = new ProgressDialog(context);
}
protected void onPreExecute(){
this.dialog.setMessage("Progress start");
this.dialog.show();
}
protected void onPostExecute(final Boolean success){
try{
if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
}
CustomListAdapter adapter = new CustomListAdapter(MainActivity.this,jsonlist, R.layout.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
lv.setAdapter(adapter);
//setListAdapter(adapter);
}catch (final IllegalArgumentException e){e.printStackTrace();}
}
protected Boolean doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
for(int i =0;i<json.length();i++) {
try {
JSONObject c = json.getJSONObject(i);
String vtitle = c.getString(TITLE);
String vdescription = c.getString(DESCRIPTION);
String vimage = c.getString(IMAGE);
/* dbHelper.createEntry(vtitle,vdescription,vimage);
dbHelper.close();*/
HashMap<String, String> map = new HashMap<>();
map.put(TITLE, vtitle);
map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
}
/*private void displaysavedlv(){
Cursor cursor = dbHelper.fetchAllCountries();
CustomCursorAdapter adapter1 = new CustomCursorAdapter(MainActivity.this,cursor);
lv.setAdapter(adapter1);
}*/
/* private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}*/
}

yes you can do this without sqlite. TinyDB will do the trick for you.
checkout here : https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo

You can create one method in sqlite that returns arrayList with hashmap :
public ArrayList<HashMap<String, String>> getAllData()
{
ArrayList<HashMap<String, String>> array_list = new ArrayList<HashMap<String, String>>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from tablename", null );
res.moveToFirst();
while(res.isAfterLast() == false){
hashmap = new HashMap<String, String>();
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
hashmap.put("columnname", res.getString(res.getColumnIndex(columnindex)));
array_list.add(hashmap);
res.moveToNext();
}
return array_list;
}
Cheers!

Related

Array index in searchview get mixed up

SearchActivity as below:
public class SearchActivity extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private SimpleCursorAdapter myAdapter;
SearchView searchView = null;
private WarehouseSalesDetails[] strArrData;
private String selectedID;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.search_item);
Toolbar toolBarSearch = (Toolbar)findViewById(R.id.toolbarSearch);
setSupportActionBar(toolBarSearch);
final String[] from = new String[]{"title"};
final int[] to = new int[]{android.R.id.text1};
//setup SimpleCursorAdapter
myAdapter = new SimpleCursorAdapter(SearchActivity.this,android.R.layout.simple_spinner_dropdown_item,null,from,to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
new RetrieveWarehouseSalesTask(this).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_search,menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager)SearchActivity.this.getSystemService(Context.SEARCH_SERVICE);
if(searchItem!=null){
searchView = (SearchView) searchItem.getActionView();
}
if(searchView!=null){
searchView.setSearchableInfo(searchManager.getSearchableInfo(SearchActivity.this.getComponentName()));
searchView.setIconified(false);
searchView.setSuggestionsAdapter(myAdapter);
//getting selected on item suggestion
searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener(){
#Override
public boolean onSuggestionClick(int position){
//Add clicked text to search box
CursorAdapter ca = searchView.getSuggestionsAdapter();
Cursor cursor = ca.getCursor();
cursor.moveToPosition(position);
searchView.setQuery(cursor.getString(cursor.getColumnIndex("title")),false);
Log.d("strArr id",strArrData[position].id);
selectedID = strArrData[position].id;
return true;
}
#Override
public boolean onSuggestionSelect(int position){
return true;
}
});
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
#Override
public boolean onQueryTextSubmit(String s){
Intent intent = new Intent(SearchActivity.this,RetrieveIndividualWarehouseSales.class);
intent.putExtra("pid",selectedID);
startActivity(intent);
return false;
}
#Override
public boolean onQueryTextChange(String s){
//filter data
final MatrixCursor mc = new MatrixCursor(new String[]{
BaseColumns._ID,"title"
});
for(int i = 0; i<strArrData.length; i++){
if(strArrData[i].title.toLowerCase().startsWith(s.toLowerCase())){
mc.addRow(new Object[]{i,strArrData[i].title});
}
}
myAdapter.changeCursor(mc);
return false;
}
});
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
return super.onOptionsItemSelected(item);
}
#Override
protected void onNewIntent(Intent intent){
if(Intent.ACTION_SEARCH.equals(intent.getAction())){
String query = intent.getStringExtra(SearchManager.QUERY);
if(searchView!=null){
searchView.clearFocus();
}
}
}
class RetrieveWarehouseSalesTask extends AsyncTask<Void,Void,Void> {
private String TAG = ActiveWarehouseSalesFragment.RetrieveWarehouseSalesTask.class.getSimpleName();
private String TAG_PID = "pid";
public ProgressDialog pDialog;
private Context context;
//URL to get JSON details
private String url = "http://example.com/example.php";
ArrayList<HashMap<String,String>> sales_details;
List<WarehouseSalesDetails> data = new ArrayList<>();
JSONObject jsonObj;
String jsonStr;
JSONArray sales;
//for recycler view
private RecyclerView warehouse_recycler;
private AdapterRecycler mAdapter;
public RetrieveWarehouseSalesTask(Context context){
this.context = context;
sales_details = new ArrayList<>();
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Searching...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0){
HttpHandler sh = new HttpHandler();
//making a request to URL and getting response
jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url (SearchActivity): " + jsonStr);
return null;
}
#Override
protected void onPostExecute(Void result){
//ArrayList<String> dataList = new ArrayList<String>();
super.onPostExecute(result);
if(pDialog.isShowing()){
pDialog.dismiss();
}
if(jsonStr != null){
try{
jsonObj = new JSONObject(jsonStr);
//Getting JSON Array Node
sales = jsonObj.getJSONArray("Result");
//looping through all results
for(int i = sales.length() - 1; i >= 0 ;i--){
JSONObject s = sales.getJSONObject(i);
WarehouseSalesDetails wsd = new WarehouseSalesDetails();
wsd.id = s.getString("id");
wsd.company_name = s.getString("company_name");
wsd.promotion_image= s.getString("promotion_image");
wsd.title = s.getString("title");
wsd.promotional_period = s.getString("promotional_period");
wsd.viewCount = s.getString("view_count");
data.add(wsd);
}
//strArrData = dataList.toArray(new String[dataList.size()]);
strArrData = data.toArray(new WarehouseSalesDetails[data.size()]);
Log.d("TAG",sales_details.toString());
}catch(final JSONException e){
Log.e(TAG, "JSON parsing error: " + e.getMessage());
}
}else{
Log.e(TAG,"Couldn't get json from server");
}
/*//update RecyclerView
warehouse_recycler = (RecyclerView)((AppCompatActivity) context).findViewById(R.id.recyclerView);
mAdapter = new AdapterRecycler(context, data);
System.out.println("mAdapter size is: " + mAdapter.getItemCount());
System.out.println("Data size is: " + data.size());
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
warehouse_recycler.setLayoutManager(layoutManager);
//mAdapter.notifyDataSetChanged();
warehouse_recycler.setAdapter(mAdapter);
warehouse_recycler.invalidate();
*/
}
}
}
I am trying to call an activity when user make a search on the search bar. I am storing id and title in strArrData. The suggestions displayed shows correct values. However, when I clicks on either of the suggestions, it always pass in the wrong id. And I found out that, the array always stores the values of the first few json values. How should I fix this ?
Found a solution by using Hashmap.
First of all store all your json values in hashmap as below:
HashMap<String, String> idMap = new HashMap<String, String>();
idMap.put(s.getString("id"),s.getString("title"));
Secondly, implement this method in your class to get the hashmap key based on hashmap value:
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
And finally:
String selectedID = getKeyFromValue(idMap,selectedTitle).toString();
Log.d("selected id",selectedID);
Intent intent = new Intent(SearchActivity.this,NextActivity.class);
intent.putExtra("pid",selectedID);
startActivity(intent);

Android studio adding custom adapter to AsyncTask

So i have a AsyncTask that pulls data from a Mysql database and displays it, currently this works fine but i need to change the simple adapter to a custom adapter so i can do more with what is displayed. But i'm not sure what i need to change in order to get my custom adapter to work with my 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;
}
}
}
The parts of interest are the custom adapter (myAdapter) located at the bottom and the first AsyncTask is what im trying to convert to a custom adapter. The onPostExecute is where the the simple adapter is and probably where i need to reference the custom adapter but need help with this
Seems you're using a single adapter for both of your needs.
Did you think about creating a two Custom Adapter classes for your two AsyncTasks.
Also few suggestions:
1. You can use Loader Callbacks and Cursor loader If you're using AsyncTask for DB fetching.
2. preExecute and postExecute already run on UI thread. So no need of runOnUIThread call there.
3. Use ViewHolder pattern in the Adapters getView method for better optimization.

how to show only selected data when spinner value is selected in android?

I have got 3 spinner where data is coming from server, if we click the search button without selecting any spinner then on next activity , it should show all list(all product without condition), but if we select according to 3 spinner then it should show only related item.I am getting all item when clicking search button without selecting anything but i am not getting selected item in next activity .
here is my Search Activity:
public class PMSearchActivity extends AppCompatActivity {
/**
* Id to identity READ_CONTACTS permission request.
*/
private static final int REQUEST_READ_CONTACTS = 0;
// UI references.
private AutoCompleteTextView mEmailView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
private ImageButton mtoolbar,pmplus;
private Button mpigeonSearchbtn;
private Spinner pmcountry;
private Spinner pmstrain;
private Spinner pmdistance;
private TextView error_text;
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmsearch);
getSupportActionBar().hide();
pmplus = (ImageButton) findViewById(R.id.plus);
pmplus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMSearchActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
finish();
}
}) ;
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMSearchActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
mpigeonSearchbtn = (Button) findViewById(R.id.pmaddcompanybtn);
mpigeonSearchbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
pmcountry = (Spinner) findViewById(R.id.sname);
pmstrain = (Spinner) findViewById(R.id.fbcountry);
pmdistance = (Spinner) findViewById(R.id.pstrain);
error_text = (TextView) findViewById(R.id.error_text);
adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems);
pmstrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems2);
pmdistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.txt, listItems3);
pmcountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void attemptLogin() {
// Reset errors.
// mEmailView.setError(null);
//mPasswordView.setError(null);
// Store values at the time of the login attempt.
String PMcountry = pmcountry.getSelectedItem().toString();
String PMstrains = pmstrain.getSelectedItem().toString();
String PMdistance = pmdistance.getSelectedItem().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
}
Intent intent = new Intent(PMSearchActivity.this, PMPigeonListingActivity.class);
intent.putExtra("Country_name", PMcountry);
intent.putExtra("Strain_name", PMstrains);
intent.putExtra("Distance_name", PMdistance);
startActivity(intent);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListStrainTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Strain-");
// Json coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems.addAll(list);
adapter.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListDistanceTask() {
}
// Json coding
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("-Select Country-");
// Json coding
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMSearchActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
here in PiegonListing activity:
public class PMPigeonListingActivity extends AppCompatActivity {
private Button mpigeonListBtn;
private ImageView mimg3;
private ImageButton mtoolbar;
private String PostCountry;
private String PostStrain;
private String PostDistance;
private Button listpigeonbutton;
private Spinner lsDistance;
private Spinner lsStrain;
private Spinner lsCountry;
private Button lssearchbutton;
private TextView listallbtn;
//Web api url
// distance part
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
ArrayList<String> listItems2 = new ArrayList<>();
ArrayAdapter<String> adapter2;
// distance part
ArrayList<String> listItems3 = new ArrayList<>();
ArrayAdapter<String> adapter3;
//Tag values to read from json
public static final String TAG_IMAGE_URL = "pimage";
public static final String TAG_NAME = "pprice";
public static final String TAG_PID = "pid";
public static final String TAG_PNAME = "pname";
public static final String TAG_PDETAILS = "pdetails";
public static final String TAG_MOBILE = "pmobile";
public static final String TAG_EMAIL = "pemail";
//GridView Object
private GridView gridView;
private GridView gridView2;
//ArrayList for Storing image urls and titles
private ArrayList<String> images;
private ArrayList<String> names;
private ArrayList<Integer> pid;
private ArrayList<String> pname;
private ArrayList<String> pdetails;
private ArrayList<String> pimage;
private ArrayList<String> pmobile;
private ArrayList<String> pemail;
//for inline search
private ArrayList<String> images2;
private ArrayList<String> names2;
private ArrayList<Integer> pid2;
private ArrayList<String> pname2;
private ArrayList<String> pdetails2;
private ArrayList<String> pimage2;
private ArrayList<String> pmobile2;
private ArrayList<String> pemail2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pmpigeon_listing);
getSupportActionBar().hide();
gridView = (GridView) findViewById(R.id.gridView);
gridView2 = (GridView) findViewById(R.id.gridView);
Bundle extras = getIntent().getExtras();
if (extras != null) {
PostCountry = extras.getString("Country_name");
PostStrain = extras.getString("Strain_name");
PostDistance = extras.getString("Distance_name");
}
images = new ArrayList<>();
names = new ArrayList<>();
pid = new ArrayList<>();
pname = new ArrayList<>();
pdetails = new ArrayList<>();
pmobile = new ArrayList<>();
pemail = new ArrayList<>();
images2 = new ArrayList<>();
names2 = new ArrayList<>();
pid2 = new ArrayList<>();
pname2 = new ArrayList<>();
pdetails2 = new ArrayList<>();
pmobile2 = new ArrayList<>();
pemail2 = new ArrayList<>();
lsStrain = (Spinner) findViewById(R.id.lsStrain);
lsDistance = (Spinner) findViewById(R.id.lsDistance);
lsCountry = (Spinner) findViewById(R.id.lsCountry);
lssearchbutton = (Button) findViewById(R.id.lssearchbutton);
listallbtn = (TextView) findViewById(R.id.listallbtn);
if (PostCountry.equals("Select Country") && PostStrain.equals("Select Strain") && PostDistance.equals("Select Distance")) {
listallbtn.setVisibility(View.GONE);
} else {
listallbtn.setVisibility(View.VISIBLE);
}
//Calling the getData method
getData();
mtoolbar = (ImageButton) findViewById(R.id.toolbar_new);
mtoolbar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMDashboardActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish(); //
return false;
}
});
lssearchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
listallbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lsCountry.getSelectedItemPosition() != 0 || lsStrain.getSelectedItemPosition() != 0 || lsDistance.getSelectedItemPosition() != 0) {
listallbtn.setVisibility(View.VISIBLE);
} else {
listallbtn.setVisibility(View.GONE);
}
lsCountry.setSelection(0);
lsStrain.setSelection(0);
lsDistance.setSelection(0);
images2.clear();
names2.clear();
pid2.clear();
pname2.clear();
pdetails2.clear();
pmobile2.clear();
pemail2.clear();
filter();
}
});
// button list
listpigeonbutton = (Button) findViewById(R.id.listpigeonbutton);
listpigeonbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(PMPigeonListingActivity.this, PMAddPigeonActivity.class);
startActivity(intent);
}
});
adapter = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems);
lsStrain.setAdapter(adapter);
ListDistanceTask distanceTask = new ListDistanceTask();
distanceTask.execute();
adapter2 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems2);
lsDistance.setAdapter(adapter2);
ListStrainTask strainTask = new ListStrainTask();
strainTask.execute();
adapter3 = new ArrayAdapter<String>(this, R.layout.spinner_small, R.id.txt, listItems3);
lsCountry.setAdapter(adapter3);
ListCountryTask listCountryTask = new ListCountryTask();
listCountryTask.execute();
}
private void getData() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......searchPigeonList";
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid.add(obj.getInt("id"));
pname.add(obj.getString("pigeon_name"));
pdetails.add(obj.getString("pigeon_details"));
pmobile.add(obj.getString("usr_mobile"));
pemail.add(obj.getString("usr_email"));
images.add(obj.getString("image"));
names.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}catch(JSONException je){
je.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}
Log.d("Test",response);
//Creating GridViewAdapter Object
PMPigeonListAdapter pmpigeonlistadapter = new PMPigeonListAdapter(getApplicationContext(), images, names, pid, pdetails, pmobile, pemail, pname);
//Adding adapter to gridview
gridView.setAdapter(pmpigeonlistadapter);
pmpigeonlistadapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("country", PostCountry);
params.put("strain", PostStrain);
params.put("distance", PostDistance);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void filter() {
//Showing a progress dialog while our app fetches the data from url
final ProgressDialog loading = ProgressDialog.show(this, "Please wait...", "Fetching data...", false, false);
String DATA_URL = "http://......hPigeonList";
final String lstrain = lsStrain.getSelectedItem().toString();
final String ldistance = lsDistance.getSelectedItem().toString();
final String lcountry = lsCountry.getSelectedItem().toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Toast.makeText(PMPigeonListingActivity.this,response,Toast.LENGTH_LONG).show();
loading.dismiss();
try {
JSONArray json = new JSONObject(response).getJSONArray("pigeon_list");
for (int i = 0; i < json.length(); i++) {
JSONObject obj = null;
try {
obj = json.getJSONObject(i);
pid2.add(obj.getInt("id"));
pname2.add(obj.getString("pigeon_name"));
pdetails2.add(obj.getString("pigeon_details"));
pmobile2.add(obj.getString("usr_mobile"));
pemail2.add(obj.getString("usr_email"));
images2.add(obj.getString("image"));
names2.add(obj.getString("pigeon_price"));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
//Creating GridViewAdapter Object
PMPigeonSearchInlineAdapter pmPigeonSearchInlineAdapter = new PMPigeonSearchInlineAdapter(getApplicationContext(), images2, names2, pid2, pdetails2, pmobile2, pemail2, pname2);
//Adding adapter to gridview
pmPigeonSearchInlineAdapter.notifyDataSetChanged();
gridView2.setAdapter(pmPigeonSearchInlineAdapter);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PMPigeonListingActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params2 = new HashMap<String, String>();
params2.put("country", lcountry);
params2.put("strain", lstrain);
params2.put("distance", ldistance);
return params2;
}
};
RequestQueue requestQueue2 = Volley.newRequestQueue(this);
gridView2.setAdapter(null);
requestQueue2.add(stringRequest);
}
public class ListStrainTask extends AsyncTask<Void, Void, Void> {
// some coding
}
// listdistancetask
public class ListDistanceTask extends AsyncTask<Void, Void, Void> {
// some coding
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems2.addAll(list);
adapter2.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsDistance.getAdapter();
lsDistance.setSelection(array_spinner.getPosition(PostDistance));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
public class ListCountryTask extends AsyncTask<Void, Void, Void> {
ArrayList<String> list;
protected ProgressDialog progressDialog;
;
ListCountryTask() {
}
#Override
protected Void doInBackground(Void... params) {
String result = "";
try {
list.add("Select Country");
// some coding
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(PMPigeonListingActivity.this, "Please wait...", "Fetching data", true, false);
list = new ArrayList<>();
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
listItems3.addAll(list);
adapter3.notifyDataSetChanged();
ArrayAdapter<String> array_spinner = (ArrayAdapter<String>) lsCountry.getAdapter();
lsCountry.setSelection(array_spinner.getPosition(PostCountry));
}
#Override
protected void onCancelled() {
// ml = null;
progressDialog.dismiss();
}
}
}
In Pigeon listing activity there is 1 option like search activity where user can search without selecting any item just like in search activity.
Set listeners for each of your spinners
setOnItemSelectedListener
In onItemSelected method , get the selected value in a variable and pass on these values to next activity.
E.g.
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String yourValue = yourSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});

Update the Progress Bar in the ListView when downloading

I have an Activity that show a list of database records .
In this activity there is a custom ListView.
In the custom ListView, there is a Button and a TextView and a ProgressBar .
My button listener that call AsyncTask is in CustomAdapter class .
DownloadTask downloadTask = new DownloadTask(getContext());
downloadTask.execute(url[position].toString());
AsynkTask work great .
But I want to update the Progress Bar during download process.
I've searched the Internet for three days but were unsuccessful.
I'm sorry for my English
public class listanimals extends ActionBarActivity {
private MyDatabase MyDataBase;
String[] listurl;
ProgressBar progressBar;
TextView url2;
CustomList adapter;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class DownloadTask extends AsyncTask<String, Integer, String> {
private Context context;
int myProgress;
public DownloadTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... sUrl) {
InputStream input = null;
final GlobalClass caches = (GlobalClass) context.getApplicationContext();
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
}
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/"+caches.getName_cach()+".mp3");
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
myProgress = (int)(total*100/connection.getContentLength());
output.write(data, 0, count);
}
} catch (Exception e) {
return e.toString();
} finally {
try {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
}
if (connection != null)
connection.disconnect();
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
//MY PROBLEM MAY HERE
progressBar.setProgress(myProgress);
}
#Override
protected void onPostExecute(String result) {
final GlobalClass caches = (GlobalClass) context.getApplicationContext();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
else{
Toast.makeText(context,"File downloaded"+ "" + caches.getName_cach(), Toast.LENGTH_SHORT).show();
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////AsynkTask end
///////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listanimals);
MyDataBase = new MyDatabase(this);
final GlobalClass caches = (GlobalClass) getApplicationContext();
final ListView listView=(ListView)findViewById(R.id.listView);
SQLiteDatabase mydb = MyDataBase.getReadableDatabase();
Cursor cursor = mydb.rawQuery("select * from animals", null);
ArrayList<String> myList = new ArrayList<String>();
final ArrayList<String> myListname = new ArrayList<String>();
ArrayList<String> myListurl = new ArrayList<String>();
try {
while(cursor.moveToNext()) {
myList.add(cursor.getString(cursor.getColumnIndex("_id")));
myListname.add(cursor.getString(cursor.getColumnIndex("name")).trim());
myListurl.add(cursor.getString(cursor.getColumnIndex("url")));
String[] listname = new String[myListname.size()];
listname = myListname.toArray(listname);
listurl = new String[myListurl.size()];
listurl = myListurl.toArray(listurl);
String[] listid = new String[myList.size()];
listid = myList.toArray(listid);
adapter = new
CustomList(listanimals.this, listname,listurl);
listView.setAdapter(adapter);
}} finally{
mydb.close();
}}
#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_main, 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);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
public class CustomList extends ArrayAdapter<String> {
private MyDatabase MyDataBase;
private final Activity context;
private final String[] web;
private final String[] url;
public CustomList(Activity context,
String[] web,String[] url) {
super(context, R.layout.list_file, web);
this.context = context;
this.web = web;
this.url = url;
}
#Override
public View getView(final int position, View view, final ViewGroup parent) {
final GlobalClass caches = (GlobalClass) context.getApplicationContext();
MyDataBase = new MyDatabase(getContext());
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.list_file, null, true);
Typeface kamran= Typeface.createFromAsset(context.getAssets(), "IranNastaliq.ttf");
progressBar=(ProgressBar)rowView.findViewById(R.id.progressBar);
TextView txtTitle3 = (TextView) rowView.findViewById(R.id.textView);
txtTitle3.setTypeface(kamran);
url2=(TextView)rowView.findViewById(R.id.textView2);
url2.setText(url[position]);
txtTitle3.setText(web[position]);
Button download=(Button)rowView.findViewById(R.id.button);
download.setTag(position);// Any data associated with the button has to be added with setTag()
download.setOnClickListener(new View.OnClickListener() {/////////call AsynkTask
#Override
public void onClick(View arg0) {
caches.setName_cach(web[position]);
DownloadTask downloadTask = new DownloadTask(getContext());
downloadTask.execute(url[position].toString());
}
});
return rowView;
}
}
}
You need to call publishProgress from the doInBackground method to update the ProgressBar: publishProgress docs
This will call onProgressUpdate(Integer... values);
You don't need the myProgress instance variable;
Check out this link https://www.youtube.com/watch?v=5HDr9FdGIVg&list=PLonJJ3BVjZW6hmkEaYIvLLm5IEGM0kpwU&index=17
You need to call - publishProgress((int) total*100/connection.getContentLength());
in the while loop
to update your progressbar.Hope it helps.
You have a progress bar in each item of the list, while you keep a single instance in the activity. This means your progress view will point to the one in the last list item that the system asked you to draw. Which might not be the one from the list item you pressed the button for. I suggest you split the classes (take them out from the activity) and you'll better see your problem. But this is going to be only the first of your problems - because you launch the async task and in the meantime you can scroll that item off screen.

Make CheckBox in ListView visible/invisible

Hey guys i am building an app that has a listview in its MainActivity. I have a checkbox on every list item but in the beggining i want it to be invisible and then when the user clicks a button in the actionbar the visibility of the checkbox to be visible. i have done this but the visibility appears only in the first item. how is it possible to make it happen to all items?
My code is
List<HashMap<String, String>> stocksList;
ArrayList<String> imageUrl;
Bitmap bmp;
public CheckBox dontShowAgain;
public Configuration newConfig;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean network_connected = activeNetwork != null
&& activeNetwork.isAvailable() && activeNetwork.isConnectedOrConnecting();
if (!network_connected) {
onDetectNetworkState().show();
} else {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
accessWebService();
registerCallClickBack();
}
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String skipMessage = settings.getString("skipMessage", "NOT checked");
if (!skipMessage.equals("checked")){
onAlertMobileData().show();
}
if(skipMessage.equals("checked")){
accessWebService();
registerCallClickBack();
}
}
}
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.Share:{
accessWebService();
registerCallClickBack();
return true;
}
case R.id.About:{
onAboutPressed().show();
return true;
}
case R.id.item1:{
CheckBox chk = (CheckBox)findViewById(R.id.checkBoxMainList);
chk.setVisibility(CheckBox.VISIBLE);
}
default:{
return false;
}
}
}
And this is where the list is being created:
public void ListDrawer() {
stocksList = new ArrayList<HashMap<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String price1 = jsonChildNode.optString("price1");
String price2 = jsonChildNode.optString("price2");
String price3 = jsonChildNode.optString("price3");
String price4 = jsonChildNode.optString("price4");
String price5 = jsonChildNode.optString("price5");
String price6 = jsonChildNode.optString("price6");
String price7 = jsonChildNode.optString("price7");
String price8 = jsonChildNode.optString("price8");
String price9 = jsonChildNode.optString("price9");
String price10 = jsonChildNode.optString("price10");
String price11 = jsonChildNode.optString("price11");
String price12 = jsonChildNode.optString("price12");
String price13 = jsonChildNode.optString("price13");
String price14 = jsonChildNode.optString("price14");
String price15 = jsonChildNode.optString("price15");
stocksList.add(createStockList(name, price, price1, price2, price3, price4, price5, price6, price7, price8, price9, price10, price11, price12, price13, price14, price15));
}
} catch (Exception e) {
//Toast.makeText(getApplicationContext(), "Error" + e.toString(),
//Toast.LENGTH_SHORT).show();
Intent intent1 = new Intent(MainActivity.this, RefreshActivity.class);
startActivityForResult(intent1, 0);
}
String[] from = { "name", "price"};
int[] to = { R.id.stock_name, R.id.stock_price};
SimpleAdapter simpleAdapter = new SimpleAdapter(this, stocksList,
R.layout.list_item,
from, to);
listView.setAdapter(simpleAdapter);
}
public HashMap<String, String> createStockList(String name, String price, String price1, String price2, String price3, String price4, String price5, String price6, String price7, String price8, String price9, String price10, String price11, String price12, String price13, String price14, String price15) {
HashMap<String, String> stockNameNo = new HashMap<String, String>();
stockNameNo.put("name", name);
stockNameNo.put("price", price);
stockNameNo.put("price1", price1);
stockNameNo.put("price2", price2);
stockNameNo.put("price3", price3);
stockNameNo.put("price4", price4);
stockNameNo.put("price5", price5);
stockNameNo.put("price6", price6);
stockNameNo.put("price7", price7);
stockNameNo.put("price8", price8);
stockNameNo.put("price9", price9);
stockNameNo.put("price10", price10);
stockNameNo.put("price11", price11);
stockNameNo.put("price12", price12);
stockNameNo.put("price13", price13);
stockNameNo.put("price14", price14);
stockNameNo.put("price15", price15);
return stockNameNo;
}
Any help will be much appreciated and accepted. Thanks in advance!
You will have to do it in your adapter instead of the activity class. In the getView method of your SimpleAdapter, trap the click event and set a boolean variable to true. In the getView method, if the boolean variable is set, show the checkboxes. If it is unset, hide the checkbox.

Categories

Resources