I have a data in JSON format which consists of city id and names. when an item is selected i want its cityid. I tried doing this. but itdoes not show correct cityid.
JSONArray gg = new JSONArray(objCity);
ArrayList<String> cityal = new ArrayList<String>();
ArrayList<String> cityalid = new ArrayList<String>();
for (int j=0; j<gg.length(); j++){
pojo = new Pojo();
JSONObject jobj = gg.getJSONObject(j);
String cityid = jobj.optString("id");
String cityName = jobj.optString("name");
cityal.add(cityName);
cityalid.add(cityid);
}
List<String> listTem = cityal;
List<String> listTemId = cityalid;
Set<String> tem = new HashSet<String>(listTem);
Set<String> temid = new HashSet<String>(listTemId);
SharedPreferences.Editor editr = getSharedPreferences("City", MODE_PRIVATE).edit();
tem.addAll(listTem);
temid.addAll(listTemId);
editr.putStringSet("cityname", tem);
editr.putStringSet("cityid", temid);
editr.commit();
and in postExecute
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("Post exec calleld", "dfds");
nDialog.dismiss();
SharedPreferences prefs = getSharedPreferences("City", MODE_PRIVATE);
Set<String> set = prefs.getStringSet("cityname", null);
Set<String> set11 = prefs.getStringSet("cityid", null);
List<String> titlesList = new ArrayList<String>(0);
titlesList.addAll(set);
List<String> descList = new ArrayList<String>(0);
descList.addAll(set11);
ssservice.clear();
for (String p : set) {
pojo = new Pojo();
pojo.setCityName(p);
al_city.add(pojo);
ssservice.add(p);
}
for (String p11 : set11) {
pojo = new Pojo();
pojo.setCityId(p11);
al_cityId.add(pojo);
ssservice11.add(p11);
}
Log.e("Cityname",""+al_city);
Log.e("City iddd", ""+al_cityId);
spinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
ssservice));
// Spinner on item click listener
spinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
ed_spinner = spinner.getSelectedItem().toString();
String idd = pojo.getCityId();
Log.e("City id from spinner",""+idd);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.textview, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder.setTitle("Select City");
// alertDialogBuilder.setIcon(R.drawable.ic_launcher);
// create alert dialog
final AlertDialog alertDialog = alertDialogBuilder.create();
final Spinner mSpinner= (Spinner) promptsView
.findViewById(R.id.c_spinner);
//mSpinner.setAdapter(ssservice);
mSpinner
.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,
ssservice));
final Button mButton = (Button) promptsView
.findViewById(R.id.c_btn);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos= mSpinner.getSelectedItemPosition();
Log.e("POS",""+pos);
pojo = new Pojo();
String cid = al_cityId.get(pos).getCityId();
Log.e("ciddddd",""+cid);
SharedPreferences.Editor editor = getSharedPreferences(
"CityIdSpinner", MODE_PRIVATE).edit();
editor.putString("id", cid);
}
});
// reference UI elements from my_dialog_layout in similar fashion
// mSpinner.setOnItemSelectedListener(new OnSpinnerItemClicked());
// show it
alertDialog.show();
alertDialog.setCanceledOnTouchOutside(false);
return;
}
This is my jsom
[{"city":[{"id":"3","name":"Pune"},{"id":"4","name":"Bhopal"},{"id":"5","name":"Indore"},{"id":"6","name":"Amravati"},{"id":"8","name":"Wardha"},{"id":"12","name":"Nagpur"},{"id":"16","name":"akola"}]
Please suggest me something.
Store your values in HashMap. cityname as Key and ID as value.
HashMap<String,String> spinnerValuesMap = new HashMap<String,String>();
for (int j=0; j<jsonArray.length(); j++){
JSONObject jobj = gg.getJSONObject(j);
String cityid = jobj.optString("id");
String cityName = jobj.optString("name")
spinnerValuesMap.put(cityName,cityid);
}
Access Id Like This:
String selectedItem= mySpinner.getSelectedItem().toString();
String cityId = spinnerValuesMap.get(selectedItem); // Your CIty id is here
Related
I have one TextView with title All Post.I'm displaying the popup window click on TextView and populate list view with two items in popup window.And trying to implement this - whenever click on list view item that item will be display in TextView and previous TextView title All Post will be add in listview in the place of clickable item.But my listview is not update on dismiss the popup window.
Here is my code of popup window.
String[] values = new String[] { "All Post", "My Post", "R-Post"};
ArrayList<String> filter_PostType = new ArrayList<String>();
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
if(str_LastSelectionValue.equals("NoVal"))
{
editor.putString("filter_post_title","All Post");
editor.commit();
}
else
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
}
textSearch.setText(str_LastSelectionValue);
Log.e("", " textSearch.getText().toString().trim() = " +
textSearch.getText().toString().trim());
textSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
popup_searchview = new PopupWindow(CustomActionActivity.this);
View layout = getLayoutInflater().inflate(R.layout.allpostsearch_popup, null);
popup_searchview.setContentView(layout);
popup_searchview.setHeight(220);
popup_searchview.setWidth(250);
popup_searchview.setOutsideTouchable(true);
popup_searchview.setFocusable(true);
popup_searchview.setBackgroundDrawable(new BitmapDrawable());
popup_searchview.showAsDropDown(v);
filter_list = (ListView) layout.findViewById(R.id.filter_ListView);
arr = new ArrayList<String>(Arrays.asList(values));
filter_PostType.clear();
for (int i = 0; i < arr.size(); i++) {
String str_PostType = arr.get(i);
if (!str_PostType.equals(str_LastSelectionValue)) {
filter_PostType.add(str_PostType);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
filter_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedFromList = (filter_list.getItemAtPosition(position).toString());
editor.putString("filter_post_title", selectedFromList);
editor.commit();
textSearch.setText(selectedFromList);
popup_searchview.dismiss();
removeItemFromList(position);
filterPost_adapter.notifyDataSetChanged();
arr = new ArrayList<String>(Arrays.asList(values));
filter_PostType.clear();
for (int i = 0; i < arr.size(); i++)
{
String str_PostType = arr.get(i);
if (!str_PostType.equals(textSearch.getText().toString().trim()))
{
filter_PostType.add(str_PostType);
int filterSize = filter_PostType.size();
Log.e(" UnMatched ", " In ListItem Click filterSize = " + filterSize);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
}
});
}
});
Use something like this:
String[] values = new String[] { "All Post", "My Post", "R-Post"};
ArrayList<String> filter_PostType = new ArrayList<String>();
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "NoVal");
if(str_LastSelectionValue.equals("NoVal"))
{
editor.putString("filter_post_title","All Post");
editor.commit();
}
else
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
}
textSearch.setText(str_LastSelectionValue);
Log.e("", " textSearch.getText().toString().trim() = " +
textSearch.getText().toString().trim());
textSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
str_LastSelectionValue = sharedPreferences.getString("filter_post_title", "");
popup_searchview = new PopupWindow(CustomActionActivity.this);
View layout = getLayoutInflater().inflate(R.layout.allpostsearch_popup, null);
popup_searchview.setContentView(layout);
popup_searchview.setHeight(220);
popup_searchview.setWidth(250);
popup_searchview.setOutsideTouchable(true);
popup_searchview.setFocusable(true);
popup_searchview.setBackgroundDrawable(new BitmapDrawable());
popup_searchview.showAsDropDown(v);
filter_list = (ListView) layout.findViewById(R.id.filter_ListView);
if(!filter_PostType.isEmpty())
filter_PostType.clear();
for (int i = 0; i < values.length; i++) {
if (!values[i].equals(str_LastSelectionValue)) {
filter_PostType.add(values[i]);
}
}
filterPost_adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.filter_popup_list_item, R.id.text_filter_title, filter_PostType);
filter_list.setAdapter(filterPost_adapter);
filter_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedFromList = (filter_list.getItemAtPosition(position).toString());
editor.putString("filter_post_title", selectedFromList);
editor.commit();
str_LastSelectionValue=selectedFromList;
textSearch.setText(selectedFromList);
popup_searchview.dismiss();
}
});
}
});
}
You don't need to change your adapter after user selects something because the next time user clicks the textview, you are making a new popup window with a new adapter.
If there is anything you don't understand, leave a comment.
Hope this helps :)
i have an app where in a form show the list view. the user can click one of the list view and when clicking the app will move to another activity and it's activity will show some data based on "code" that sent from the list view form. my app is success to move in another activity but doesn't show the data. please help me.
Thank you.
This is my code in list view form :
final ListView lv = (ListView)findViewById(R.id.lv);
String url = "http://192.168.43.244/wewash/listview.php";
try {
JSONArray data = new JSONArray(getJSONUrl(url));
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("nama", c.getString("nama"));
map.put("tanggal_keluar", c.getString("tanggal_keluar"));
MyArrList.add(map);
}
SimpleAdapter sAdap;
sAdap = new SimpleAdapter(halaman_utama.this, MyArrList, R.layout.listview,
new String[] {"nama", "tanggal_keluar","id", ""}, new int[] {R.id.tsnama, R.id.tstglk, R.id.kode, R.id.tsspasi});
lv.setAdapter(sAdap);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String kode = ((TextView) findViewById(R.id.kode)).getText().toString();
Intent in = new Intent(halaman_utama.this, p_daftar_pakaian.class);
//menampilkan value dari item yg diklik
in.putExtra("id", kode);
startActivity(in);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and it's my code in new activity :
Intent intent = getIntent();
String kode = intent.getStringExtra("id");
String url = "http://192.168.43.244/wewash/listview_detail.php?id="+kode;
try {
JSONArray data = new JSONArray(getJSONUrl(url));
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
String idpk = c.getString("id");
String namapk = c.getString("nama");
String paketpk = c.getString("paket");
String cbiasapk = c.getString("cbiasa");
String ckhususpk = c.getString("ckhusus");
String tglantarpk = c.getString("tanggal_keluar");
String totalpk = c.getString("total");
// String nomorpk = c.getString("no_hp");
atasnama.setText(namapk);
ereview.setText("Id Pelanggan : " +idpk+
"\nNama Pelanggan : "+namapk+
"\nPaket : "+paketpk+
"\nCucian Biasa : "+cbiasapk+" kg"+
"\nCucian Khusus : "+ckhususpk+" item"+
"\nTotal : "+totalpk+" rupiah"+
"\nTanggal Antar : "+tglantarpk);
// enomer.setText(nomorpk);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
and it's the php file
<?php
mysql_connect("localhost","root","");
mysql_select_db("wewash");
$kode=$_GET["id"];
$sql=mysql_query("select * from pakaian where id='$kode'");
$arrayId=array();
if($sql === FALSE) {
die(mysql_error());
}
while($row=mysql_fetch_array($sql)){
$arrayId["id"]=$row["id"];
$arrayId["nama"]=$row["nama"];
$arrayId["tanggal_keluar"]=$row["tanggal_keluar"];
$arrayId["paket"]=$row["paket"];
$arrayId["cbiasa"]=$row["cbiasa"];
$arrayId["ckhusus"]=$row["ckhusus"];
$arrayId["total"]=$row["total"];
}
echo json_encode($arrayId);
?>
The aim of the application is to have spinners left (home team) and on the right (Away team). I can successfully populate the home team spinners but when i try to populate the away team spinners i get the error:
06-25 18:02:36.052: W/System.err(17916): org.json.JSONException: Value at 0 is null.
06-25 18:02:36.057: W/System.err(17916): at org.json.JSONArray.get(JSONArray.java:259)
06-25 18:02:36.057: W/System.err(17916): at org.json.JSONArray.getJSONObject(JSONArray.java:480)
06-25 18:02:36.057: W/System.err(17916): at app.league.npd.CaptainsInfo.useaJson(CaptainsInfo.java:309)
I can see that the error is coming from the "ateam" array, but i dont know what the problem is. I am new to android programming so any help would be appreciated.
Here is the code:
public class CaptainsInfo extends Activity {
JSONArray jsonArray = null;
JSONArray str_login = null;
public String items[];
public String aitems[];
private Spinner
spinner1, spinner2, spinner3, spinner4,
spinner5, spinner6, spinner7, spinner8,
spinner9, spinner10, spinner11, spinner12,
spinner13, spinner14;
private Button btnSubmit;
public String kode;
public String Home_team;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
addListenerOnSpinner2ItemSelection();
}
public void addItemsOnSpinner(String items[]) {
spinner3 = (Spinner) findViewById(R.id.player11);
spinner5 = (Spinner) findViewById(R.id.player12);
spinner7 = (Spinner) findViewById(R.id.player21);
spinner9 = (Spinner) findViewById(R.id.player22);
spinner11 = (Spinner) findViewById(R.id.player31);
spinner13 = (Spinner) findViewById(R.id.player32);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner3.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner5.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner7.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner9.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner11.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner13.setAdapter(adapter);
}
public void addItemsOnSpinner2(String aitems[]) {
spinner4 = (Spinner) findViewById(R.id.aplayer11);
spinner6 = (Spinner) findViewById(R.id.aplayer12);
spinner8 = (Spinner) findViewById(R.id.aplayer21);
spinner10 = (Spinner) findViewById(R.id.aplayer22);
spinner12 = (Spinner) findViewById(R.id.aplayer31);
spinner14 = (Spinner) findViewById(R.id.aplayer32);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner4.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner6.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner8.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner10.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner12.setAdapter(adapter);
adapter = new ArrayAdapter<String>(
this,android.R.layout.simple_spinner_item, aitems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner14.setAdapter(adapter);
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.h_type);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//String test1 = parent.getItemAtPosition(position).toString();
String test = (String) spinner1.getSelectedItem();
//String test2 = (String) spinner2.getSelectedItem();
items=useJson(test);
//aitems=useaJson(test2);
//addItemsOnSpinner2(aitems);
addItemsOnSpinner(items);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });}
public void addListenerOnSpinner2ItemSelection(){
spinner2 = (Spinner) findViewById(R.id.a_type);
spinner2.setOnItemSelectedListener(new CustomOnItemSelectedListener());
spinner2.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//String test2 = parent.getItemAtPosition(position).toString();
//String test = (String) spinner1.getSelectedItem();
String test2 = (String) spinner2.getSelectedItem();
// items=useJson(test);
aitems=useaJson(test2);
addItemsOnSpinner2(aitems);
//addItemsOnSpinner(items);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
} });
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.h_type);
spinner2 = (Spinner) findViewById(R.id.a_type);
spinner3 = (Spinner) findViewById(R.id.player11);
spinner4 = (Spinner) findViewById(R.id.aplayer11);
spinner5 = (Spinner) findViewById(R.id.player12);
spinner6 = (Spinner) findViewById(R.id.aplayer12);
spinner7 = (Spinner) findViewById(R.id.player21);
spinner8 = (Spinner) findViewById(R.id.aplayer21);
spinner9 = (Spinner) findViewById(R.id.player22);
spinner10 = (Spinner) findViewById(R.id.aplayer22);
spinner11 = (Spinner) findViewById(R.id.player31);
spinner12 = (Spinner) findViewById(R.id.aplayer31);
spinner13 = (Spinner) findViewById(R.id.player32);
spinner14 = (Spinner) findViewById(R.id.aplayer32);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(CaptainsInfo.this,
"OnClickListener : " +
"\nSpinner 1 : " + String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : " + String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
String links_url = "http://192.168.9.59/NPD/detail-info.php?Match_id="+kode;
// Call the FunctionParser to parse the information being returned
// From the FHL databaseList<NameValuePair> params = new ArrayList<NameValuePair>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.FunctionParser(links_url);
// The array is called and the information is returned from
// the database corresponding to each string below
try {
str_login = json.getJSONArray("temp");
String jdwl = "";
TextView isi = (TextView) findViewById(R.id.fixdet);
for(int i = 0; i < str_login.length(); i++){
JSONObject ar = str_login.getJSONObject(i);
Home_team = ar.getString("Home_team");
jdwl += "" + ar.getString("Home_team")+"\n vs \n"+
"" + ar.getString("Away_team")+"\n"+
"" + ar.getString("Fixture_date")+"\n";
}
isi.setText(jdwl);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String[] useJson(String test) {
JSONParser jParser = new JSONParser();
String link_url = "http://10.2.0.0/NPD/P_name.php?"+test;
JSONObject json = jParser.FunctionParser(link_url);
try {
jsonArray = json.getJSONArray("team");
items = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
items[i]=jsonObject.getString("name");
}
return(items);}
catch (JSONException e) {
e.printStackTrace();
}
return items;
}
public String[] useaJson(String test2) {
JSONParser jjParser = new JSONParser();
String links_url = "http://10.2.0.0/NPD/P_name1.php?"+test2;
JSONObject json = jjParser.FunctionParser(links_url);
try {
jsonArray = json.getJSONArray("ateam");
aitems = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
aitems[i]=jsonObject.getString("name");
}
return(aitems);}
catch (JSONException e) {
e.printStackTrace();
}
return aitems;
}
}
According to json.org (http://www.json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)):
getJSONObject throws JSONException if there is no value for the index
or if the value is not a JSONObject.
How your ateam array is being populated? Seems that you are adding null values inside it. Make sure that your ateam array is populated only with initialized JSONObject, maybe the JSONObject is null when you add it to ateam array so you must check if is null before adding it to ateam.
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
}
}
Hi, I have a listview and i'm wanting it so that when you press on an item it stores your selection in shared preferences. The purpose for this is so that next time I open the app it skips the selection process.
So what I'm wanting to know is how do I incorporate this function into my code?
Here is my code so far:
public class SelectTeamActivity extends ListActivity {
public String fulldata = null;
public String position = null;
public String divisionName= null;
public List<String> teamsList = null;
public String divName = null;
protected void loadData() {
fulldata = getIntent().getStringExtra("fullData");
position = getIntent().getStringExtra("itemIndex");
Log.v("lc", "selectteamActivity:" + fulldata);
Log.v("lc", "position:" + position);
int positionInt = Integer.parseInt(position);
try{
JSONObject obj = new JSONObject(fulldata);
teamsList = new ArrayList<String>();
JSONObject objData = obj.getJSONObject("data");
JSONArray teamInfoArray = objData.getJSONArray("structure");
for(int r = 0; r < teamInfoArray.length(); r++ ){
JSONObject teamFeedStructureDict = teamInfoArray.getJSONObject(r);
JSONArray teamStructureArray =
(JSONArray) teamFeedStructureDict.get("divisions");
JSONObject teamFeedDivisionsDictionary =
teamStructureArray.getJSONObject(positionInt);
divName = teamFeedDivisionsDictionary.getString("name");
JSONArray teamNamesArray =
(JSONArray) teamFeedDivisionsDictionary.get("teams");
for(int t = 0; t < teamNamesArray.length(); t++){
JSONObject teamNamesDict = teamNamesArray.getJSONObject(t);
teamsList.add(teamNamesDict.getString("name"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.selectact);
loadData();
TextView headerText = (TextView) findViewById(R.id.header_text);
headerText.setText(divName);
TextView redHeaderText = (TextView) findViewById(R.id.redheadertext);
redHeaderText.setText("Please select your team:");
setListAdapter( new ArrayAdapter<String>(this, R.layout.single_item,
teamsList));
ListView list = getListView();
list.setTextFilterEnabled(true);
}
#Override
protected void onListItemClick (ListView l, View v, int position, long id) {
Intent intent = new Intent(this, HomeActivity.class);
String curPos = Integer.toString(position);
//or just use the position:
intent.putExtra("itemIndex", curPos);
intent.putExtra("fullData", fulldata); //or just the part you want
startActivity(intent);
}
}
In your Activity's onCreate():
SharedPreferences preferences = getSharedPreferences("preferences", MODE_WORLD_WRITEABLE);
In your onListItemClick():
preferences.edit().putInt("KEY", position).commit();
Everywhere in your project:
int position = preferences.getInt("KEY", -1);
(-1 is a default value that means when there is no value with the given key, return this value)