I have gridview which load few images thumbnails. When I click on some image is opened in new activity full image. Now I trying to add some description about the image. When activity is loaded the info for this image is loaded also. So far so good..
The problem comes when I click on button next which load next image(full image without to back on the gridview with thumbnails) the description doesn't update and change for the next image. Is just same description for every image.
Here I download thumb, full_image and description,
String url = "http://myhost/get.php?id=" + my_id;
JSONArray data;
try {
resultServer = getJSONUrl(url);
data = new JSONArray(resultServer);
MyArrList = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("id", (String)c.getString("id"));
map.put("description", (String)c.getString("description"));
// Thumbnail Get ImageBitmap To Bitmap
map.put("ImagePathThum", (String)c.getString("image"));
map.put("ImageThumBitmap", (Bitmap)loadBitmap(c.getString("image")));
// Full (for View Full)
map.put("ImagePathFull", (String)c.getString("image_big"));
MyArrList.add(map);
}
Then this is the gridView() which display thumbs
public void ShowAllContent()
{
// gridView1
final GridView gridV = (GridView)findViewById(R.id.gridView1);
gridV.setAdapter(new ImageAdapter(act1.this,MyArrList));
// OnClick
gridV.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
String Position = String.valueOf(position);
Intent newActivity = new Intent(act1.this,act2.class);
newActivity.putExtra("Position", Position);
newActivity.putExtra("resultServer", resultServer);
newActivity.putExtra("description", MyArrList.get(position).get("description").toString());
startActivity(newActivity);
finish();
}
});
}
Then In act2
TextView txtView;
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
txtView = (TextView) findViewById(R.id.text);
Intent intent= getIntent();
curPosition = Integer.parseInt(intent.getStringExtra("Position"));
resultServer = String.valueOf(intent.getStringExtra("resultServer"));
textDescription = getIntent().getStringExtra("description");
((TextView)findViewById(R.id.text)).setText(textDescription+"");
try {
MyArrList = ConvertJSONtoArrayList(resultServer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("ArrayList Size",String.valueOf(MyArrList.size()));
// Show Image Full
new DownloadFullPhotoFileAsync().execute();
// Button Back
back = (Button) findViewById(R.id.btnBack);
back.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
curPosition = curPosition - 1;
new DownloadFullPhotoFileAsync().execute();
}
});
// Button Next
next = (Button) findViewById(R.id.btnNext);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
curPosition = curPosition + 1;
new DownloadFullPhotoFileAsync().execute();
}
});
}
// Show Image Full
public void ShowImageFull(String imageName, Bitmap imgFull)
{
// Prepare Button (Back)
if(curPosition <= 0)
{
back.setEnabled(false);
}
else
{
back.setEnabled(true);
}
// Prepare Button (Next)
Log.d("curPosition",String.valueOf(curPosition));
Log.d("MyArrList.size",String.valueOf(MyArrList.size()));
if(curPosition >= MyArrList.size() - 1)
{
next.setEnabled(false);
}
else
{
next.setEnabled(true);
}
ImageView image = (ImageView) findViewById(R.id.fullimage);
try
{
image.setImageBitmap(imgFull);
} catch (Exception e) {
// When Error
image.setImageResource(android.R.drawable.ic_menu_report_image);
}
// Show Toast
Toast.makeText(act2.this,imageName,Toast.LENGTH_LONG).show();
}
public ArrayList<HashMap<String, Object>> ConvertJSONtoArrayList(String json) throws JSONException
{
JSONArray data = new JSONArray(resultServer);
ArrayList<HashMap<String, Object>> arr = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, Object>();
map.put("ImageName", (String)c.getString("name"));
map.put("ImagePathThum", (String)c.getString("image"));
map.put("ImagePathFull", (String)c.getString("image_big"));
map.put("description", (String)c.getString("description"));
arr.add(map);
}
return arr;
}
}
public class DownloadFullPhotoFileAsync extends AsyncTask<String, Void, Void> {
String strImageName = "";
String ImageFullPhoto = "";
Bitmap ImageFullBitmap = null;
#Override
protected Void doInBackground(String... params) {
strImageName = MyArrList.get(curPosition).get("ImageName").toString();
ImageFullPhoto = MyArrList.get(curPosition).get("ImagePathFull").toString();
ImageFullBitmap = (Bitmap)loadBitmap(ImageFullPhoto);
return null;
}
}
I'm sorry for long source code but I don't know which part exactly is needed.
I've tried to add in DownloadFullPhotoFileAsync
textDescription = MyArrList.get(curPosition).get("description").toString();
so when is loaded new DownloadFullPhotoFileAsync().execute(); in button next to load also this but I guess this is wrong since it doesn't work.
You can't setText in DoInBackground() function in Async Task, but you can do a setText of your description on PostExecute() which is a function of AsyncTask.
So i think you should try to set your description in PostExecute function in your Asynctask.
take a look at : http://developer.android.com/reference/android/os/AsyncTask.html
I hope this help,
Cheers !
Related
i want to have a search bar that searches a number that has been typed in (for example: 115048) and put that in a listview. the json file looks like this http://api.ccapp.it/v1/student/115048/schedule/11
hope someone can help me, the code that i use right now to search a link is like this but it doesnt have a search bar:
public class RoosterviewMd extends ListActivity {
Button mButton;
EditText mEdit;
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String id = null;
//private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
private static String url = "http://api.ccapp.it/v1/student/115048/schedule/12";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosterviewmd);
//Number input
final EditText input = (EditText) findViewById(R.id.editText2);
//buttons for all the days
Button btn2 = (Button) findViewById(R.id.button29);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Je ziet je rooster voor maandag al" , Toast.LENGTH_SHORT ).show();
}
});
Button btnOne = (Button)findViewById(R.id.button30);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDi.class);
startActivity(intent);
}
});
Button btnTwo = (Button)findViewById(R.id.button31);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewWo.class);
startActivity(intent);
}
});
Button btnThree = (Button)findViewById(R.id.button32);
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDo.class);
startActivity(intent);
}
});
Button btnFour = (Button)findViewById(R.id.button33);
btnFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewVr.class);
startActivity(intent);
}
});
//Buttons end here
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String lesson = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String teacher = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
String room = ((TextView) view.findViewById(R.id.room))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(RoosterviewMd.this);
pDialog.setMessage("Give me a second please");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr1 = jsonObj.getJSONArray("lessons");
JSONArray arr2 = arr1.getJSONArray(0); //Dag
for (int b = 0; b < arr2.length(); b++) {
JSONObject c = arr2.getJSONObject(b);
String lesson = c.getString(TAG_LESSON);
String teacher = c.getString(TAG_TEACHER);
String room = c.getString(TAG_ROOM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, lesson);
contact.put(TAG_TEACHER, teacher);
contact.put(TAG_ROOM, room);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("CCApp", "Couldn't get any data from the url");
Toast.makeText(getBaseContext(),"We are aware of this error and are working on it, in the mean time eat a cookie", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(RoosterviewMd.this, contactList,
R.layout.list_item, new String[] {TAG_LESSON, TAG_TEACHER,
TAG_ROOM }, new int[] { R.id.lesson,
R.id.teacher, R.id.room });
setListAdapter(adapter);
}
}
}
i hope someone can help me with this
Check out this answer: Get text from web page to string
Basically, you can simply get the text from the page and pass it into a string, and search the string application side for the contents of your edit text.
If you're looking for more functionality with the data from the web site, I would pull the Json into an array of Jsonobjects using something like Gson. You'd then be able to use the data from the web page in a bit more of a structured manner.
Edit: Now to actually answer your question.
You can include an edit text and button in your xml in order to search using a basic search bar kinda thing.
To set a listener on the button, you would do something like:
findViewById(R.id.button).setOnClickListener(new OnClickListener(){
#Override
protected void onClick(View v){
//Here, we can control what the response to the button press is, and grab the text in the edit text field.
String editTextString = findViewById(R.id.edittext).getEditableText().toString();
//Now we have a string used to parse the json or whatever else you need to do.
//May want to add a case here if editTextString is null to prevent runtime errors.
}
}
(Forgive me if there's any minor syntatic errors, just wrote that up quick here in the browser, no API to check on it. :))
in my app i have a listview(asynctask) getting all the users from external database. Each row of my listview contains an image that the user can interact. When user presses that image i try to start a new intent by using the data that i already have(by using putExtra while starting the intent.) Listview works fine - it gathers all the data from database. But, the putExtra values are same for each row. I will appreciate if you can help me regarding that matter.
Code is as follows;
The important part is below
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
where i try to add putExtra.
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
//Invitation count
Integer inv = json.getInt("invitation");
setNotifCount(inv);
if(Integer.parseInt(res) == 1) {
// Getting JSON Array from URL
android1 = json.getJSONArray(TAG_LOCATIONDATA);
for (int i = 0; i < android1.length(); i++) {
JSONObject c = android1.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString("username");
final String dataenlem = c.getString("enlem");
final String databoylam = c.getString("boylam");
final String datazaman = c.getString("zaman");
/*----------to get City-Name from coordinates ------------- */
StringBuffer address = new StringBuffer();
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(Double.parseDouble(dataenlem), Double.parseDouble(databoylam), 1);
if (addresses.size() > 0)
// System.out.println(addresses.get(0).getLocality());
address.append(addresses.get(0).getAddressLine(1))
.append(",").append(addresses.get(0).getAddressLine(2));
} catch (IOException e) {
e.printStackTrace();
}
String datalokasyon = address.toString();
/*----------to get City-Name from coordinates ------------- */
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put("enlem", dataenlem);
map.put("boylam", databoylam);
map.put("zaman", datazaman);
map.put("lokasyon", datalokasyon);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
BaseAdapter adapter = new SimpleAdapter(UserList.this, oslist,
R.layout.listview_userlist,
new String[]{TAG_VER,"zaman","lokasyon"}, new int[]{
R.id.vers,R.id.lastlocationinput,R.id.lastupdatedinput}) {
public View getView (int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
showlastonmap.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent login = new Intent(getApplicationContext(),
HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", dataenlem);
login.putExtra("boylam", databoylam);
startActivity(login);
}
});
return v;
}
};
SwingBottomInAnimationAdapter animationAdapter = new SwingBottomInAnimationAdapter(adapter);
animationAdapter.setAbsListView(list);
list.setAdapter(animationAdapter);
}
//admob
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
//admob
}
if(Integer.parseInt(res) == 0) {
new SweetAlertDialog(UserList.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText(getString(R.string.userlist_nofriend))
.show();
}
}
else {
return;
}
}catch
(JSONException e) {
e.printStackTrace();
}
}
}
you should do :
Intent login = new Intent(getApplicationContext(),
HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", oslist.get(position).get("enlem"));
login.putExtra("boylam", oslist.get(position).get("boylam"));
startActivity(login);
You have to create new object which contains required fields.
class Data {
String dataenlem;
String databoylam;
Data(String dataenlem, String databoylam) {
...
}
}
and then set corresponding to each row data using setTag method
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
// add this
showlastonmap.setTag(new Data(dataenlem, databoylam));
and get it on your onClick
public void onClick(View v) {
// and this
Data data = (Data)v.getTag();
Intent login = new Intent(getApplicationContext(),HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", data.dataenlem);
login.putExtra("boylam", data.databoylam);
startActivity(login);
}
this app should show thumbnail , title, and the duration of each video in the playlist selected , but thumbnail remain white
the application works but It don't show the thumbnail of the video in the playlist
how can I do ? you have any solution?
THIS IS MY CODE
public class MainActivity extends Activity {
ImageView mainThumb;
TextView mainTitle;
TextView mainTime;
LinearLayout videos;
ArrayList<String> links;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.videos);
new ParseVideoDataTask().execute();
mainThumb = (ImageView) findViewById(R.id.mainThumb);
mainTitle = (TextView) findViewById(R.id.mainTitle);
mainTime = (TextView) findViewById(R.id.mainTime);
videos = (LinearLayout) findViewById(R.id.videos);
}
private class ParseVideoDataTask extends AsyncTask<String, String, String> {
int count = 0;
#Override
protected String doInBackground(String... params) {
URL jsonURL;
URLConnection jc;
links = new ArrayList<String>();
try {
jsonURL = new URL("http://gdata.youtube.com/feeds/api/playlists/" +
"PL-7t9DoIELCRF7F7bZvvBwO1yvHRFsJiu" +
"?v=2&alt=jsonc");
//PL_VGbflD64WSR1MBcpWlNwsY0lRNVuJ3r
jc = jsonURL.openConnection();
InputStream is = jc.getInputStream();
String jsonTxt = IOUtils.toString(is);
JSONObject jj = new JSONObject(jsonTxt);
JSONObject jdata = jj.getJSONObject("data");
JSONArray aitems = jdata.getJSONArray("items");
for (int i=0;i<aitems.length();i++) {
JSONObject item = aitems.getJSONObject(i);
JSONObject video = item.getJSONObject("video");
String title = video.getString("title");
JSONObject player = video.getJSONObject("player");
String link = player.getString("default");
String length = video.getString("duration");
JSONObject thumbnail = video.getJSONObject("thumbnail");
String thumbnailUrl = thumbnail.getString("hqDefault");
String[] deets = new String[4];
deets[0] = title;
deets[1] = thumbnailUrl;
deets[2] = length;
links.add(link);
publishProgress(deets);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(final String... deets) {
count++;
if (count == 1) {
MainActivity.setImageFromUrl(deets[1], mainThumb, MainActivity.this);
mainTitle.setText(deets[0]);
mainTime.setText(formatLength(deets[2]));
mainThumb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(1)));
startActivity(i);
}
});
} else {
LayoutInflater layoutInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View video = layoutInflater.inflate(R.layout.video, null);
ImageView thumb = (ImageView) video.findViewById(R.id.thumb);
TextView title = (TextView) video.findViewById(R.id.title);
TextView time = (TextView) video.findViewById(R.id.time);
MainActivity.setImageFromUrl(deets[1], thumb, MainActivity.this);
title.setText(deets[0]);
time.setText(formatLength(deets[2]));
video.setPadding(20, 20, 20, 20);
videos.addView(video);
video.setId(count-1);
video.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(links.get(v.getId())));
startActivity(i);
}
});
}
}
}
private CharSequence formatLength(String secs) {
int secsIn = Integer.parseInt(secs);
int hours = secsIn / 3600,
remainder = secsIn % 3600,
minutes = remainder / 60,
seconds = remainder % 60;
return ((minutes < 10 ? "0" : "") + minutes
+ ":" + (seconds< 10 ? "0" : "") + seconds );
}
public static void setImageFromUrl(String string, ImageView mainThumb2,
MainActivity mainActivity) {
}
#Override
public void onDestroy() {
super.onDestroy();
for (int i=0;i<videos.getChildCount();i++) {
View v = videos.getChildAt(i);
if (v instanceof ImageView) {
ImageView iv = (ImageView) v;
((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
}
}
}
}
Use Picasso to set the image url like so:
Picasso.withContext(this).load(thumbnailUrl).into(myImageView);
To do this you'll need to return the JSON object in the doInBackground method, or use something like Retrofit (as I mentioned in the comment above) to get a nice POJO and return that. Then in the postExecute you can use the thumbnail url in the JSON (or POJO) and set it using Picasso above. Picasso will take care of downloading and caching the image for you and loading it into the image view.
I know there are many questions asking about returning to the last position scrolled when the list has been refreshed. However I don't know why in my case (Adapter) the given answers don't work.
I have an adapter where at a given time it refreshes with new info and loads it in the adapter. What I want is that when it refreshes not come again to the top of the adapter and save the previous state.
Here is the code I use.
OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
setListAdapter(adapter);
candidatosList = new ArrayList<HashMap<String, String>>();
The asynctask is divided in 2 parts. The retrieval of information and adapting the data into the adapter.
Here is the code of adapting it:
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_ID,TAG_NSERIE,TAG_TABLET,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA,TAG_CORRECTAS, TAG_ERRORES},
new int[] { R.id.autoid,R.id.id,R.id.tablet, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria, R.id.correctas, R.id.fallos});
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
}
But how should I save the state of the adapter and then start showing the items considering the previous state.
Thank you
Edit: I have tried the answer approbed here Maintain/Save/Restore scroll position when returning to a ListView, but I cannot make it work.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
setListAdapter(adapter);
candidatosList = new ArrayList<HashMap<String, String>>();
lv = (ListView)findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String idd = ((TextView) view.findViewById(R.id.dni)).getText()
.toString();
Intent in = new Intent(getApplicationContext(),
MonitDetail.class);
in.putExtra("idd", idd);
startActivityForResult(in, 100);
}
});
}
//
//
public void timer(){
new CountDownTimer(tiempo, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
index = lv.getFirstVisiblePosition();
v = lv.getChildAt(0);
top = (v == null) ? 0 : v.getTop();
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
}
}.start();}
class CargarCandidatos extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
monitorizar();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_ID,TAG_NSERIE,TAG_TABLET,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA,TAG_CORRECTAS, TAG_ERRORES},
new int[] { R.id.autoid,R.id.id,R.id.tablet, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria, R.id.correctas, R.id.fallos});
lv.setSelectionFromTop(index, top);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
});
}
}
public void monitorizar() throws Exception{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fecha",Titulacion.fecha()));
JSONObject json = jParser.makeHttpRequest(url_candidatos, "GET", params);
ArrayList<HashMap<String, String>> temp;
temp = new ArrayList<HashMap<String, String>>();
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
candidatos = json.getJSONArray(TAG_CANDIDATOS);
for (int i = 0; i < candidatos.length(); i++) {
JSONObject c = candidatos.getJSONObject(i);
String id = c.getString(TAG_ID);
String nserie = c.getString(TAG_NSERIE);
String tablet = c.getString(TAG_TABLET);
String dni = c.getString(TAG_DNI);
String nombre = c.getString(TAG_NOMBRE);
String test = c.getString(TAG_TEST);
String pregunta = c.getString(TAG_PREGUNTA);
String bateria = c.getString(TAG_BATERIA);
String correctas = c.getString(TAG_CORRECTAS);
String errores = c.getString(TAG_ERRORES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NSERIE, nserie);
map.put(TAG_TABLET, tablet);
map.put(TAG_DNI, dni);
map.put(TAG_NOMBRE, nombre);
map.put(TAG_TEST, test);
map.put(TAG_PREGUNTA, pregunta);
map.put(TAG_BATERIA, bateria);
map.put(TAG_CORRECTAS, correctas);
map.put(TAG_ERRORES, errores);
temp.add(map);
candidatosList = temp;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You can use like this
getListView().setSelection(position);
method of your ListView.
where you can get 'position' from the length of list you are passing to the adapter.
Declare you listview Globally and then you can keep the last position before New-Data-call. After then you can call listview for a position selection.
I would like to display the data from MySql in a listview using a search parameter in my application.
I've succeeded, but the problem I'm having is that every time I push the search button twice, both sets of result data are shown in the ListView, whereas I only want to display the latest set of results.
This is the code I'm using:
public class ListPerusahaan extends ListActivity {
/** Called when the activity is first created. */
private static final String TAG_ID = "id";
private static final String TAG_NAMA = "nama_perusahaan";
private static final String TAG_PEKERJAAN = "pekerjaan";
private static final String TAG_ALAMAT= "alamat";
private static final String TAG_DEADLINE = "deadline";
EditText keyword; Button search; private ProgressDialog pDialog; ArrayList<HashMap<String, String>> DataList; // JSONArray perusahaan = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listperusahaan);
keyword=(EditText)findViewById(R.id.Editsearch);
search=(Button)findViewById(R.id.search);
DataList = new ArrayList<HashMap<String, String>>();
search.setOnClickListener(new View.OnClickListener()
{
#Override public void onClick(View v) {
// TODO Auto-generated method stub
if (keyword.getText().toString().length() == 0 ) {
Toast toast = Toast.makeText(getApplicationContext(),"Please enter your keyword", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else {
new searchData().execute();
}
}
});
}
#SuppressLint("NewApi") public class searchData extends AsyncTask<Void, Void, Void>
{
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListPerusahaan.this);
pDialog.setMessage("Loading ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
List<NameValuePair> paramemeter = new ArrayList<NameValuePair>();
paramemeter.add(new BasicNameValuePair("keyword", keyword.getText().toString()));
JSONObject json = JSONParser.getJSONFromUrl("http://10.0.2.2/appmysql/dataperusahaan.php", paramemeter);
try{
JSONArray perusahaan = json.getJSONArray("perusahaan");
if (perusahaan != null)
{
for(int i=0;i<perusahaan.length();i++){
// HashMap<String, String> map1 = new HashMap<String, String>();
JSONObject jsonobj = perusahaan.getJSONObject(i);
// Storing each json item in variable
String id = jsonobj.getString(TAG_ID);
String nama_perusahaan = jsonobj.getString(TAG_NAMA);
String pekerjaan = jsonobj.getString(TAG_PEKERJAAN);
String alamat = jsonobj.getString(TAG_ALAMAT);
String deadline = jsonobj.getString(TAG_DEADLINE);
// creating new HashMap
HashMap<String, String> map1 = new HashMap<String, String>();
// adding each child node to HashMap key => value
map1.put(TAG_ID, id);
map1.put(TAG_NAMA, nama_perusahaan);
map1.put(TAG_PEKERJAAN, pekerjaan);
map1.put(TAG_ALAMAT, alamat);
map1.put(TAG_DEADLINE, deadline);
// adding HashList to ArrayList
DataList.add(map1);
}
}
else {
Toast toast= Toast.makeText(getApplicationContext(), "No data found", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
catch(JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListPerusahaan.this, DataList,R.layout.row,
new String[] { TAG_NAMA, TAG_PEKERJAAN, TAG_ALAMAT, TAG_DEADLINE },
new int[] { R.id.nama_perusahaan, R.id.pekerjaan, R.id.alamat,R.id.deadline});
// updating listview
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(ListPerusahaan.this, "Perusahaan '" + o.get("nama_perusahaan") + "' was clicked.", Toast.LENGTH_SHORT).show();
*/
// getting values from selected ListItem
String nama = ((TextView) view.findViewById(R.id.nama_perusahaan)).getText().toString();
String pekerjaan = ((TextView) view.findViewById(R.id.pekerjaan)).getText().toString();
String alamat = ((TextView) view.findViewById(R.id.alamat)).getText().toString();
String deadline = ((TextView) view.findViewById(R.id.deadline)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), detail_lowongan.class);
in.putExtra(TAG_NAMA, nama);
in.putExtra(TAG_PEKERJAAN, pekerjaan);
in.putExtra(TAG_ALAMAT, alamat);
in.putExtra(TAG_DEADLINE, deadline);
startActivity(in);
}
});
}
});
}
}
}
Edit: in onclick clear DataList
search.setOnClickListener(){
......
DataList.clear(); //in onclick method
}
I am not sure whether you are looking for this or not...but if you don't want to allow duplicates in your list try ....
When the data filled in your list
Set<type> set=new Hashset(yourlist);
ArrayList<type> nodupList=new ArrayList<type>();
noduplist.addAll(set);
using this way it will remove the duplicates in your list
Edit:
Try this
After for loop
Set<HashMap> set=new HashSet(DataList);
ArrayList<HashMap> nodupList=new ArrayList<HashMap>();
nodupList.addAll(set);
DataList.clear();
DataList.addAll(nodupList);
try it may help you
Clear the DataList of the ArrayList type before populating it in the for loop.