i don't know how to make a function to show the next/previous detail data by clicking the next/previous button based on listview.
This is the screenshot that i want to do
My listview Activity
My Detail data Activity, to show next/previous data from listview
EDIT : i have a listview data (use xml parser), and pass the data to new acitivity called "Detail_toko.class" :
List<NameValuePair> paramemeter = new ArrayList<NameValuePair>();
paramemeter.add(new BasicNameValuePair("keyword", "a"));
// paramemeter.add(new BasicNameValuePair("kategori",Category.getSelectedItem().toString()));
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL, paramemeter); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(TAG_DETAIL);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(TAG_ID, parser.getValue(e, TAG_ID));
map.put(TAG_NAMATOKO, parser.getValue(e, TAG_NAMATOKO));
map.put(TAG_KATEGORI, parser.getValue(e, TAG_KATEGORI));
map.put(TAG_EMAIL, parser.getValue(e, TAG_EMAIL));
map.put(TAG_ICON, parser.getValue(e, TAG_ICON));
// adding HashList to ArrayList
PremiumList.add(map);
}
return null;
}
/**
* Updating parsed JSON data into ListView
* */
list=(ListView)findViewById(R.id.listview);
if(PremiumList.size() > 0)
{
adapter=new LazyAdapterStore(ListPerusahaan.this, PremiumList);
list.setAdapter(adapter);
}
else
{
Toast toast= Toast.makeText(getApplicationContext(), "No data found, enter another keyword", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String nama_toko = ((TextView) view.findViewById(R.id.nama_toko)).getText().toString();
String kategori = ((TextView) view.findViewById(R.id.kategori)).getText().toString();
String email = ((TextView) view.findViewById(R.id.email)).getText().toString();
PremiumList = new ArrayList<HashMap<String, String>>();
Intent in = new Intent(ListPerusahaan.this, Detail_toko.class);
in.putExtra("PremiumList", PremiumList);
//in.putStringArrayListExtra( "PremiumList", PremiumList );
in.putExtra("position", position);
in.putExtra("TotalData", TotalData);
in.putExtra(TAG_NAMATOKO, nama_toko);
in.putExtra(TAG_KATEGORI, kategori);
in.putExtra(TAG_EMAIL, email);
startActivity(in);
This is my LazyAdapterStore code :
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_data_store, null);
TextView nama_toko = (TextView)vi.findViewById(R.id.nama_toko); // title
TextView kategori = (TextView)vi.findViewById(R.id.kategori); // title
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
TextView email = (TextView)vi.findViewById(R.id.email); // artist name
HashMap<String, String> detail = new HashMap<String, String>();
detail = data.get(position);
// Setting all values in listview
nama_toko.setText(detail.get(ListPerusahaan.TAG_NAMATOKO));
kategori.setText(detail.get(ListPerusahaan.TAG_KATEGORI));
email.setText(detail.get(ListPerusahaan.TAG_EMAIL));
imageLoader.DisplayImage(detail.get(ListPerusahaan.TAG_ICON), thumb_image);
return vi;
}
EDIT : and, this is my new activity "Detail_Toko" to display detail data from listview items :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this must be called BEFORE setContentView
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.detail_toko);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
call_btn=(Button)findViewById(R.id.call);
email_btn=(Button)findViewById(R.id.email);
sms_btn=(Button)findViewById(R.id.sms);
Next_btn=(Button)findViewById(R.id.Next);
Prev_btn=(Button)findViewById(R.id.Prev);
phonenumber=(TextView)findViewById(R.id.telpon);
// getting intent data
Intent in = getIntent();
// #SuppressWarnings("unchecked")
//ArrayList<HashMap<String, String>> PremiumList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("PremiumList");
// Get String values from previous intent
final String nama_toko = in.getStringExtra(TAG_NAMATOKO);
final String kategori = in.getStringExtra(TAG_KATEGORI);
final String email = in.getStringExtra(TAG_EMAIL);
// Get Int values from previous intent
final int posisi = in.getExtras().getInt("position");
final int Total_data = in.getExtras().getInt("TotalData");
/*
Bundle bundle = in.getExtras();
HashMap<String, String> list = (HashMap<String, String>) bundle.getSerializable("PremiumList");
list = data.get(currentposition);
*/
Bundle bundle = in.getExtras();
HashMap<String, String> list = (HashMap<String, String>) bundle.getSerializable("PremiumList");
list = data.get(currentposition);
// Displaying all values on the screen
lblPosisi = (TextView) findViewById(R.id.namatoko);
lbltotaldata = (TextView) findViewById(R.id.nama);
lblNamatoko = (TextView) findViewById(R.id.nama_toko);
lblKategori = (TextView) findViewById(R.id.kategori);
lblEmail = (TextView) findViewById(R.id.textemail);
lblPosisi.setText(String.valueOf(posisi));
lbltotaldata.setText(String.valueOf(Total_data));
lblNamatoko.setText(nama_toko);
lblKategori.setText(kategori);
lblEmail.setText(email);
// Set the int value of currentposition from previous selected listview item
currentposition = posisi;
Next_btn.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
if(currentposition >= Total_data - 1)
{
Toast toast= Toast.makeText(getApplicationContext(), "Last Record", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else
{
currentposition++;
lblPosisi.setText(String.valueOf(currentposition));
lblNamatoko.setText(list.get(nama_toko));
lblKategori.setText(list.get(kategori));
lblEmail.setText(list.get(email));
}
}
});
Prev_btn.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
if(currentposition <= 0)
{
Toast toast= Toast.makeText(getApplicationContext(), "First Record", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else
{
currentposition--;
lblPosisi.setText(String.valueOf(currentposition));
lblNamatoko.setText(list.get(nama_toko));
lblKategori.setText(list.get(kategori));
lblEmail.setText(list.get(email));
}
}
});
the problem is, i don't know how to make a function to show the next/previous detail data from listview by clicking the next/previous button in "Detail_toko" activity.
Please someone Help me...
Thank in advance
Just seen your request on last post.
Solution given by Parvaz is perfect, you just need to figure out the code.
You have an arraylist "PremiumList" which is responsible for your listview rows data.
All you need is to pass position and this list to Detail_toko.class (via intent using parceable or declaring arraylist as static (not recommended) etc. ) and your solution will be couple of steps away.
In Detail_toko.class create a global variable currentPosition which will get its value from past activity like TAG_NAMATOKO from intent.
Then in onClickListener of NEXT button increment 1 to currentPosition and get detail from your arraylist you have just transported from last activity as you have done in your getView method.
HashMap<String, String> detail = new HashMap<String, String>();
detail = data.get(currentPosition);
// Setting all values in listview
nama_toko = detail.get(ListPerusahaan.TAG_NAMATOKO);
kategori = detail.get(ListPerusahaan.TAG_KATEGORI);
email = detail.get(ListPerusahaan.TAG_EMAIL);
Set these values and your new view will be updated accordingly.
In onClickListener of PREVIOUS button decrement 1 from currentPosition, followed by same code (which means you must create a method and call that, no code repetition).
Try it. This is as detailed as we can explain without actually doing your homework !
EDIT :
First of all remove this line from OnItemClick
PremiumList = new ArrayList<HashMap<String, String>>();
You are clearing all the data from PremiumList in this line and this way you will get blank list in next activity. So get rid of this line.
Once you will get PremiumList in your next activity, all you need is position and totalData along with it in intent extra.
You can get rid of TAG_NAMATOKO, TAG_KATEGORI,TAG_EMAIL from your intent extra.
I had told you to not to repeat the code, as you are beginner it is very important for you to follow as it will make your life easy by
taking such considerations and making your habbit.
Now your code in "Detail_Toko" will become:
HashMap<String, String> list = null;
int currentposition = 0;
int Total_data =0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this must be called BEFORE setContentView
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.detail_toko);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
call_btn=(Button)findViewById(R.id.call);
email_btn=(Button)findViewById(R.id.email);
sms_btn=(Button)findViewById(R.id.sms);
Next_btn=(Button)findViewById(R.id.Next);
Prev_btn=(Button)findViewById(R.id.Prev);
phonenumber=(TextView)findViewById(R.id.telpon);
// Displaying all values on the screen
lblPosisi = (TextView) findViewById(R.id.namatoko);
lbltotaldata = (TextView) findViewById(R.id.nama);
lblNamatoko = (TextView) findViewById(R.id.nama_toko);
lblKategori = (TextView) findViewById(R.id.kategori);
lblEmail = (TextView) findViewById(R.id.textemail);
// getting intent data
Bundle bundle = getIntent().getExtras();
// Get Int values from previous intent
currentposition = bundle.getInt("position");
Total_data = bundle.getInt("TotalData");
list = (HashMap<String, String>) bundle.get("PremiumList");
setView();
Next_btn.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
if(currentposition >= Total_data - 1)
{
Toast toast= Toast.makeText(getApplicationContext(), "Last Record", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else
{
currentposition++;
setView();
}
}
});
Prev_btn.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
if(currentposition <= 0)
{
Toast toast= Toast.makeText(getApplicationContext(), "First Record", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_VERTICAL|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
else
{
currentposition--;
setView();
}
}
});
private void setView()
{
if(list != null && list.size() > currentposition)
{
HashMap<String, String> detail = new HashMap<String, String>();
detail = list.get(currentposition);
lblPosisi.setText(String.valueOf(currentposition));
lbltotaldata.setText(String.valueOf(Total_data));
lblNamatoko.setText(detail.get(ListPerusahaan.TAG_NAMATOKO));
lblKategori.setText(detail.get(ListPerusahaan.TAG_KATEGORI));
lblEmail.setText(detail.get(ListPerusahaan.TAG_EMAIL));
}
}
Suggestion: Use ViewHolder to populate view in getView Method, it will make your adapter "An efficent adapter". (search for examples)
Follow naming convention and all.
Check anyObject != null , their size or length before using them and bundle.containKey etc stuff to avoid fatal exception like nullPointerException.
Just pass the PremiumList ArrayList to your Detail_toko Activity...either pass it by Intent or get it directly from the getter methods. Then in your Detail_toko activity on each next / previous button click increment the position of arraylist to get the data and then populate accordingly.
This is how you will pass your arraylist
Passing ArrayList through Intent
and instead of getting the rest of the data from intent get the data from the arraylist.
like arraylist.get(index).
just like this
/********Instead of getting your values like this*******************/
String nama_toko = in.getStringExtra(TAG_NAMATOKO);
String kategori = in.getStringExtra(TAG_KATEGORI);
String email = in.getStringExtra(TAG_EMAIL);
/************************Use a method like given here How to do the next button action?****************************/
//The method setvalue would be quite useful for you where you will pass the int j parameter to get appropriate values. If next button is clicked increment the j if previous button is clicked decrement it. and then display your values asusual.
// Displaying all values on the screen
lblNamatoko = (TextView) findViewById(R.id.namatoko);
lblKategori = (TextView) findViewById(R.id.kategori);
lblEmail = (TextView) findViewById(R.id.textemail);
lblNamatoko.setText(nama_toko);
lblKategori.setText(kategori);
lblEmail.setText(email);
Related
what im trying to do is look at the json pull all the names to a list view(save the imdbid of that names) and from there you can click on a movie and it will go to a new intent that will bring you the movie that you clicked on with its name summary and an image
im searching in a json with an array in it that looks like this(it based on what the user searched so this is one example...)
{"Search":[{"Title":"Batman Begins","Year":"2005","imdbID":"tt0372784","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"},{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","imdbID":"tt2975590","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTE5NzU3MTYzOF5BMl5BanBnXkFtZTgwNTM5NjQxODE#._V1_SX300.jpg"},{"Title":"Batman","Year":"1989","imdbID":"tt0096895","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"},{"Title":"Batman Returns","Year":"1992","imdbID":"tt0103776","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BODM2OTc0Njg2OF5BMl5BanBnXkFtZTgwMDA4NjQxMTE#._V1_SX300.jpg"},{"Title":"Batman Forever","Year":"1995","imdbID":"tt0112462","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNWY3M2I0YzItNzA1ZS00MzE3LThlYTEtMTg2YjNiOTYzODQ1XkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Batman & Robin","Year":"1997","imdbID":"tt0118688","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM1NTIyNjkwM15BMl5BanBnXkFtZTcwODkxOTQxMQ##._V1_SX300.jpg"},{"Title":"Batman: The Animated Series","Year":"1992–1995","imdbID":"tt0103359","Type":"series","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU3MjcwNzY3NF5BMl5BanBnXkFtZTYwNzA2MTI5._V1_SX300.jpg"},{"Title":"Batman: Under the Red Hood","Year":"2010","imdbID":"tt1569923","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMwNDEyMjExOF5BMl5BanBnXkFtZTcwMzU4MDU0Mw##._V1_SX300.jpg"},{"Title":"Batman: The Dark Knight Returns, Part 1","Year":"2012","imdbID":"tt2313197","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ##._V1_SX300.jpg"},{"Title":"Batman: Mask of the Phantasm","Year":"1993","imdbID":"tt0106364","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMzODU0NTYxN15BMl5BanBnXkFtZTcwNDUxNzUyMQ##._V1_SX300.jpg"}],"totalResults":"310","Response":"True"}
so what i want to do is get the imdbid when he clicks on the listview which contains the movie name
this is what i tried:
JSONObject jsonObject = new JSONObject(finalJson);
JSONArray parentArray = jsonObject.getJSONArray("Search");
StringBuffer finalStringBuffer = new StringBuffer();
String imdbid ;
for (int i=0; i<parentArray.length(); i++){
JSONObject finalJsonObject = parentArray.getJSONObject(i);
String movieName = finalJsonObject.getString("Title");
nameOfMovie.add(movieName);
String year = finalJsonObject.getString("Year");
yearOfMovie.add(year);
String omdbID = finalJsonObject.getString("imdbID");
id.add(omdbID);
finalStringBuffer.append(movieName + " , " + year + " , " + omdbID + "\n");
imdbid = omdbID ;
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
but how can i know the imdbid(which is in the movie name that is displayed in a list) that he cliked on?
listview code:
listViewInternetScreen.setClickable(true);
listViewInternetScreen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long i) {
Intent intenttoEditScreen=new Intent(AddFromInternet.this, EditMovie.class);
setResult(RESULT_OK,intenttoEditScreen);
String jsonMovieName = String.valueOf(nameOfMovie);
String jsonMovieSummery = String.valueOf(yearOfMovie);
String jsonImageURL = String.valueOf(id);
intenttoEditScreen.putExtra("json", jsonMovieName);
intenttoEditScreen.putExtra("json", jsonMovieSummery);
intenttoEditScreen.putExtra("json", jsonImageURL);
startActivity(intenttoEditScreen);
}
});
and the search method:
btnGo = (Button) findViewById(R.id.btnGo);
assert btnGo != null;
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MAKE A SEARCH STRING AND PARSE THE RESULT
final String search = "http://www.omdbapi.com/?s=" + EtSearch.getText().toString();
Log.e("JSON", search);
new JSONParser().execute(search);
ArrayList<String> list = new ArrayList<>(nameOfMovie);
arrayAdapter = new ArrayAdapter<>(AddFromInternet.this,
android.R.layout.simple_list_item_1, list);
arrayAdapter.notifyDataSetChanged();
listViewInternetScreen.setAdapter(arrayAdapter);
Log.e("JSON MOVIE", String.valueOf(nameOfMovie));
}
});
thanks for any help :D
Step 1: Use Gson (and Retrofit, if you'd like) to simplify turning a JSON string into a list of Java objects
Step 2: Make a custom ArrayAdapter that loads this list of objects. Then, when you add an Item click listener, you can get that object from the list item you clicked, and start the Intent for showing the full info for that movie.
Additional step would be to make the Movie object Parcelable, so you can add the object to the Intent in one line, rather than each individual field it contains
I have a custom listview with checkbox imageview and textview and there is a button below listview. On clicking of that button i have to pass all the checked item details to another activity and show in other listview. I am able to pass selected value but not able to pass images. Images are in drawable folder. Please help me thanks.
Here is the code:
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = "";
ArrayList<Item> stList = ((OurServiceAdapter) nAdapter)
.getAllData();
for (int i = 0; i < stList.size(); i++) {
Item singleStudent = stList.get(i);
if (singleStudent.isCheckbox() == true) {
name.add(singleStudent.getName().toString());
img.add(singleStudent.getImage());
data = data + "\n" + singleStudent.getName().toString();
}
}
// byte[] imgs = singleStudent.getImage();
Intent intent = new Intent(ActivityOurServices.this, ActivityServicesForm.class);
intent.putStringArrayListExtra("key", name);
//intent.putIntegerArrayListExtra("img", img);
startActivity(intent);
}
});
}
you can pass all image as Integer arrayList :
//first : for each imageView inside list you must to set tag ,for example ;
imageView0.setTag(R.drawable.image_0);
imageView1.setTag(R.drawable.image_1);
.
.
.
imageViewN.setTag(R.drawable.image_N);
now when you press button :
ArrayList<Integer> checkedImageSrcId = new ArrayLIst<Integer> ;
for (int i = 0; i < stList.size(); i++) {
Item singleStudent = stList.get(i);
if (singleStudent.isCheckbox() == true) {
name.add(singleStudent.getName().toString());
// img.add(singleStudent.getImage());
// you most to get checked imageViews Tag and i dont have an idea about how to get those
checkedImageSrcId.add( getImageViewTagAtPostion(i));
data = data + "\n" + singleStudent.getName().toString();
}
}
// byte[] imgs = singleStudent.getImage();
Intent intent = new Intent(ActivityOurServices.this, ActivityServicesForm.class);
intent.putStringArrayListExtra("key", name);
intent.putIntegerArrayListExtra("img", checkedImageSrcId);
startActivity(intent);
I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).
I have a ListView that utilizes a CheckedTextView and a clear all button that has the following code:
btnClearAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int listsize = songsList.size();
filelv = (ListView)getView().findViewById(R.id.FileList);
checkedCount = 0;
for (int i=0; i<listsize-1; i++) {
// if(currentPlayList.get(i).equals ("Checked")){
songsList.get(i).get("songCheckedStatus").equals("Not Checked");
filelv.setItemChecked(i, false);
}
}
});
When the code executes, each array "songsList" value is set to "Not Checked" correctly, so I know that the button is working. However, the CheckedTextView items are not "unticking".
Where am I going wrong?
olution:
As mentioned above, I just set up a global variable and passed whether I wanted to Select All or Clear All to it. Then I just called my function for populating the ListView. As the ListView is built, it checks the variable in a simple "if" statement, and adds whether to check or uncheck. The cursor adapter then does the check/uncheck as it reruns.
//The code for clearing all.
btnClearAll.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
checkedCount = 0;
GetMusicMode = "ClearAll";
GetMusic getMusic = new GetMusic();
getMusic.execute();
}
});
And this from my data grabber for the ListView.
....
String track_Title = null;
String track_Path = null;
String track_Artist = null;
String track_Album = null;
String track_ID = null;
String track_TrackNumber = null;
String track_AlbumID = null;
String track_ArtistID = null;
String track_Checked = null;
if (Constants.GetMusicMode.equals("SelectAll")){
track_Checked = "Checked";
}else{
track_Checked = "Not Checked";
}
.....
.....
HashMap<String, String> song = new HashMap<String, String>();
song.put("songTitle", track_Title);
song.put("songPath", track_Path);
song.put("songArtist", track_Artist);
song.put("songAlbum", track_Album);
song.put("songTrackNumber", track_TrackNumber);
song.put("songID", track_ID);
song.put("songAlbumID", track_AlbumID);
song.put("songArtistID", track_ArtistID);
song.put("songCheckedStatus", track_Checked);
// Adding each song to SongList
songsList.add(song);
....throw to cursor adapter
and finally, this section from the cursoradapter getview
if (songsList.get(position).get("songCheckedStatus").equals("Checked")){
holder.checkTextView.setChecked(true);
}else{
holder.checkTextView.setChecked(false);
}
i have an app that is showing data in listview ,but i want first row to be inflated by diferent layout , and i did that but since there is gona be a big number of listitems , i want to optimize listview and there is issue. i cant optimize listview when iam filling listview on that way , so how can i put content that should go in fist row inside listview header witch is inflated by some layout ,here is the code of Adapter
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
refLayout.setVisibility(View.GONE);
mBtnNaslovnica = (Button) findViewById(R.id.mBtnNaslovnica);
mBtnNaslovnica.setSelected(true);
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
loadPage();
ImageButton mBtnRefresh = (ImageButton) findViewById(R.id.btnRefresh);
mBtnRefresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoadingTask().execute(URL);
}
});
}
public void loadPage(){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(getIntent().getStringExtra("json"));
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void reloadPage(String jsonstring){
ArrayList<HashMap<String, String>> homeList = new ArrayList<HashMap<String, String>>();
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonstring);
JSONObject datajson = jsonobj.getJSONObject("data");
JSONArray news = datajson.getJSONArray(TAG_NEWS);
JSONArray actual = datajson.getJSONArray("actual");
for(int i = 0; i < news.length(); i++){
JSONObject c = news.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String title = c.getString(TAG_TITLE);
String story = c.getString(TAG_STORY);
String shorten = c.getString(TAG_SH_STORY);
String author = c.getString(TAG_AUTHOR);
String datetime = c.getString(TAG_DATETIME);
String img = c.getString(TAG_IMG);
String big_img = c.getString(TAG_BIG_IMG);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TITLE, title);
map.put(TAG_STORY, story);
map.put(TAG_IMG, img);
map.put(TAG_BIG_IMG, big_img);
map.put(TAG_DATETIME, datetime);
map.put(TAG_AUTHOR, author);
// adding HashList to ArrayList
homeList.add(map);}
for(int i = 0; i < actual.length(); i++){
JSONObject c = actual.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ACT_TIME);
String body = c.getString(TAG_ACT_BODY);
String anews = " | "+ id+ " " + body;
String cur_anews = ((TextView) findViewById(R.id.scroller)).getText().toString();
String complete = anews + cur_anews;
TextView anewstv = (TextView) findViewById(R.id.scroller);
anewstv.setText(complete);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter=new LazyAdapter(this, homeList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String cur_title = ((TextView) view.findViewById(R.id.title)).getText().toString();
String cur_story = ((TextView) view.findViewById(R.id.einfo2)).getText().toString();
String cur_author = ((TextView) view.findViewById(R.id.einfo1)).getText().toString();
String cur_datetime = ((TextView) view.findViewById(R.id.tVdatetime)).getText().toString();
String cur_actual = ((TextView) findViewById(R.id.scroller)).getText().toString();
ImageView cur_img = (ImageView) view.findViewById(R.id.list_image);
String cur_img_url = (String) cur_img.getTag();
Intent i = new Intent("com.example.androidhive.CURENTNEWS");
i.putExtra("CUR_TITLE", cur_title);
i.putExtra("CUR_STORY", cur_story);
i.putExtra("CUR_AUTHOR", cur_author);
i.putExtra("CUR_DATETIME", cur_datetime);
i.putExtra("CUR_IMG_URL", cur_img_url);
i.putExtra("CUR_ACTUAL", cur_actual);
startActivity(i);
}
});
}
public void startNewActivity(){
}
public class LoadingTask extends AsyncTask<String, Object, Object>{
XMLParser parser = new XMLParser();
JSONParser jParser = new JSONParser();
LinearLayout content = (LinearLayout) findViewById(R.id.content);
LinearLayout refLayout = (LinearLayout) findViewById(R.id.refLayout);
protected void onPreExecute(){
content.setClickable(false);
refLayout.setVisibility(View.VISIBLE);
}
#Override
protected Object doInBackground(String... params) {
// TODO Auto-generated method stub
String URL = params[0];
JSONObject json = jParser.getJSONFromUrl(URL);
//String xml = parser.getXmlFromUrl(URL); // getting XML from URL
// getting DOM element
return json;
}
protected void onPostExecute(Object result){
String json;
json = result.toString();
reloadPage(json);
refLayout.setVisibility(View.GONE);
}
}
}
If I got your point - you can go with 2 approaches:
Add headerView to the list. That is just easy as inflate your View and pass it to
addHeaderView(View) of your List. Note: you must add this view before setting the adapter, or it will throw the exception.
However, as your 'header' is representing the same data as all other items, but has different layout - I suggest not to use Header here. Instead, try to implement getItemViewType() in your adapter. http://developer.android.com/reference/android/widget/BaseAdapter.html#getItemViewType(int)
If you'll do - you'll have ability to check which type of layout to return in getView() method. And Android will take care of optimizing and reusing your inflated Views for you, so you can be sure that convertView, passed to your getView will be of the right type and layout.
Please let me know if I should explain with more details.
You can do it like this:
...
convertView.setOnClickListener(new OnItemClick(position));
...
public class OnItemClick implements OnClickListener {
private final int index;
public OnItemClick(int _index) {
this.index = _index;
}
#Override
public void onClick(View v) {
//dosomething
}
}