I am new to android development. I have implemented an activity which is Loading Json data to a listview. I have two activities now. First one is login Activity.Second one is loading list view activity.the json data is loading perfectly. but my problem is, when i pressed back button, the list view data is removing one by one. i have no idea where the problem is.
here is my main activity
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
ImageButton login;
public static ArrayList<HashMap<String, String>> oslist;
//URL to get JSON Array
private static String url = "http://api.learn2crack.com/android/jsonos/";
//JSON Node Names
static final String TAG_OS = "android";
static final String TAG_VER = "ver";
static final String TAG_NAME = "name";
static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loging);
oslist = new ArrayList<HashMap<String, String>>();
login = (ImageButton)findViewById(R.id.imageButton1);
new ArrayList<HashMap<String, String>>();
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.title);
name = (TextView)findViewById(R.id.artist);
api = (TextView)findViewById(R.id.time);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... arg0) {
// TODO Auto-generated method stub
JsonParser jParser = new JsonParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// TODO Auto-generated method stub
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
Intent reult = new Intent(MainActivity.this,ViewList.class);
//reult.putStringArrayListExtra("map", oslist);
//startActivity(reult);
reult.putExtra("arraylist", oslist);
startActivityForResult(reult, 500);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Here is my Listview Activity
public class ViewList extends Activity {
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Intent getres = getIntent();
//HashMap<String, String> hashMap = (HashMap<String, String>)getres.getSerializableExtra("map");
final ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
ListView list=(ListView)findViewById(R.id.list);
/* ListAdapter adapter = new SimpleAdapter(ViewList.this, arl,
R.layout.row,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.title,R.id.artist, R.id.time});*/
NewsRowAdapter adapter = new NewsRowAdapter(ViewList.this, R.layout.row, arl);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(ViewList.this, "You Clicked at "+arl.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
}
this is my Adapter Class
public class NewsRowAdapter extends BaseAdapter {
/*//ArrayList<HashMap<String, String>> arl = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("arraylist");
//ArrayList<HashMap<String, String>> data;
private List<Item> items;
//private Item objBean;
private int row;*/
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<HashMap<String, String>> data;
int resource;
//String response;
//Context context;
//Initialize adapter
public NewsRowAdapter(Activity act, int resource,ArrayList<HashMap<String, String>> d) {
super();
this.resource=resource;
this.data = d;
this.activity = act;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/*public NewsRowAdapter(Activity act, int resource, HashMap<String, List<String>> listChildData)) {
super(act, resource, arrayList);
this.activity = act;
this.row = resource;
this.data = arrayList;
}*/
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View vi = convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.row,null);
TextView title = (TextView) vi.findViewById(R.id.title);
TextView artist = (TextView) vi.findViewById(R.id.artist);
TextView time = (TextView) vi.findViewById(R.id.time);
ImageView img = (ImageView) vi.findViewById(R.id.list_image);
HashMap<String, String> song = new HashMap<String, String>();
song =data.get(position);
title.setText(song.get(MainActivity.TAG_VER));
artist.setText(song.get(MainActivity.TAG_NAME));
time.setText(song.get(MainActivity.TAG_API));
//imageLoader.DisplayImage(song.get(CustomizedListView.KEY_THUMB_URL), img);
Button accept = (Button) vi.findViewById(R.id.btnaccept);
accept.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//CustomizedListView getlist = new CustomizedListView();
final int x = (int) getItemId(position);
Toast.makeText(parent.getContext(),"you clicked "+ x , Toast.LENGTH_SHORT).show();
}
});
vi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(), "view clicked: " , Toast.LENGTH_SHORT).show();
}
});
return vi;
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int possision) {
// TODO Auto-generated method stub
return possision;
}
#Override
public long getItemId(int possision) {
// TODO Auto-generated method stub
return possision;
}
}
please some one help me...
Yes it will do so, When you press back button your activity get finished , So the view inside the activity will get deleted , Either you must keep the data in a seperate class, outside activity or keep the activity alive.
Related
I am developing an app using api to display list, and listview contains data. But when i run the project, activity shows blank result and logcat shown 'no value of "program"(i.e.array name)' message.
How do i show result of following code?
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String AID = "asanaid";
static String ANAME = "asananame";
static String DURATION = "duration";
static String IMGURL = "imgeurl";
static String IMGVERSION = "imgeversion";
static String AUDIOURL = "audiourl";
static String AUDIOVERSION = "audioversion";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_relaxation_lv);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://www.....");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("program");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("asanaid", jsonobject.getString("asanaid"));
map.put("asananame", jsonobject.getString("asananame"));
map.put("duration", jsonobject.getString("duration"));
map.put("imgeurl", jsonobject.getString("imgeurl"));
map.put("imgeversion", jsonobject.getString("imgeversion"));
map.put("audiourl", jsonobject.getString("audiourl"));
map.put("audioversion", jsonobject.getString("audioversion"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
public class ListViewAdapter extends BaseAdapter{
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView tvAname, tvId, imgUrl, imgVersion, audioUrl, audioVersion, duration;
ImageView imgPose;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.relaxationlv_single_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
tvAname = (TextView) itemView.findViewById(R.id.lv_aname);
tvAname.setText(resultp.get(MainActivity.ANAME));
tvId = (TextView)itemView.findViewById(R.id.lv_aid);
tvId.setText(resultp.get(MainActivity.AID));
duration = (TextView)itemView.findViewById(R.id.lv_duration);
duration.setText(resultp.get(MainActivity.DURATION));
imgVersion = (TextView)itemView.findViewById(R.id.lv_imgversion);
imgVersion.setText(resultp.get(MainActivity.IMGURL));
audioVersion = (TextView)itemView.findViewById(R.id.lv_audioversion);
audioVersion.setText(resultp.get(MainActivity.AUDIOVERSION));
audioUrl= (TextView)itemView.findViewById(R.id.lv_audiourl);
audioUrl.setText(resultp.get(MainActivity.AUDIOURL));
imgPose = (ImageView)itemView.findViewById(R.id.lv_imgurl);
imageLoader.DisplayImage(resultp.get(MainActivity.IMGURL), imgPose);
// Capture ListView item click
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, RelaxationLvAudioPlayerActivity1.class);
intent.putExtra("asanaid", resultp.get(MainActivity.AID));
intent.putExtra("asananame", resultp.get(MainActivity.ANAME));
intent.putExtra("duration", resultp.get(MainActivity.DURATION));
intent.putExtra("imgeurl", resultp.get(MainActivity.IMGURL));
intent.putExtra("imgeversion", resultp.get(MainActivity.IMGVERSION));
intent.putExtra("audiourl", resultp.get(MainActivity.AUDIOURL));
intent.putExtra("audioversion", resultp.get(MainActivity.AUDIOVERSION));
context.startActivity(intent);
}
});
return itemView;
}
}
You are getting the JSONException -
Please check if one of the following field is missing in your JSON Response -
map.put("asanaid", jsonobject.getString("asanaid"));
map.put("asananame", jsonobject.getString("asananame"));
map.put("duration", jsonobject.getString("duration"));
map.put("imgeurl", jsonobject.getString("imgeurl"));
map.put("imgeversion", jsonobject.getString("imgeversion"));
map.put("audiourl", jsonobject.getString("audiourl"));
map.put("audioversion", jsonobject.getString("audioversion"));
You can check this buy printing the value of jsonobject.getString("asaname") and so on.
Or the another case might be the value is of different dataType. E.g. audioversion you are trying to get as String but in JSON it is type of Integer.
i am quiet new to android. please help me out with this doubt.
i have created a image slider.
and i have an API i want to load the images from those API into slider.
i have created a Activity file.
public class MoreImage extends Activity {
ImageView ProductImage;
private ConnectionDetector cd;
UserFunctions userFunction;
ProgressDialog mProgressDialog;
JSONObject jsonobject,jsonobj1;
JSONObject jsonobj_prodPriceDetails, jsonobj_RUPEE;
HListView listView;
Button img_buy_now;
String Vendor_id=null;
SharedPreferences pref;
String Store_id_pref=null;
String item_id_pref=null;
EditText edt_search;
public static Typeface font;
String from=null;
RelativeLayout pb_progress;
GridView related_grid;
ImageView add_cart;
String full_path_re;
static TextView notifCount;
ListView list;
SrollviewAdapter scrAdapter;
JSONArray jsonarray = null;
JSONArray jsonarray1=null;
JSONArray json_store_array = null;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<HashMap<String, String>> store_arraylist;
String images;
static String PRODUCT_IMAGES = "image_list";
static String COUNT = "count";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_item);
userFunction = new UserFunctions();
cd = new ConnectionDetector(getApplicationContext());
arraylist = new ArrayList<HashMap<String, String>>();
new DownloadJSON().execute();
pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Vendor_id=pref.getString("user_id", null);
Store_id_pref=pref.getString("store_id", null);
item_id_pref = pref.getString("item_id", null);
getActionBar().setDisplayHomeAsUpEnabled(true);
setTitle("Product List");
getActionBar().setIcon(R.drawable.ic_launcher);
Intent myIntent = getIntent();
from = myIntent.getStringExtra("from");
font = Typeface.createFromAsset(getBaseContext().getAssets(),
"fonts/Amaranth-Regular.otf");
if (cd.isConnectingToInternet()) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
//pb_progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
jsonobject = userFunction.imageG("9");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("image_gallery");
jsonarray1 =jsonobj1.getJSONArray("count");
String s= jsonarray1.toString();
System.out.print("jsonarray1:::::"+jsonarray1);
int b= Integer.parseInt(s);
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("image_list", jsonobject.getString("image_list"));
map.put("count","jsonarray1");
arraylist.add(map);
System.out.print("all data::::::"+map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
PagerAdapter adapter = new MoreImageAdapter(MoreImage.this);
viewPager.setAdapter(adapter);
//pb_progress.setVisibility(View.GONE);
}
}
}
and this is a page adapter file
public class MoreImageAdapter extends PagerAdapter{
HashMap<String, String> resultp = new HashMap<String, String>();
Context context;
int count1;
// int[] imageId = {
// R.drawable.slide1,
// R.drawable.slide2,
// R.drawable.unfollow,
// R.drawable.facebook_icon,
// R.drawable.ic_launcher,
// R.drawable.follow_unfollow,};
public MoreImageAdapter(Context context){
this.context = context;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
View viewItem = inflater.inflate(R.layout.image_item, container, false);
ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
imageView.setImageResource(imageId[position]);
((ViewPager)container).addView(viewItem);
return viewItem;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return imageId.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
// TODO Auto-generated method stub
return view == ((View)object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
((ViewPager) container).removeView((View) object);
}
}
there are two json objects one is image and other is count. image contains more then 1 image.
i am able to get the data from json parsing in activity class but i want to set the data in page adapter class as that shows my slider.
so how can i pass those value i got in activity file to page adapter class???
please help......
You can pass those values using the constructor.
PagerAdapter adapter = new MoreImageAdapter(MoreImage.this, String images, ArrayList<Sting> something,...);
then in the MoreImageAdapter get those images from constructor
public MoreImageAdapter(Context context, String images, ArrayList<String> something,...){
this.context = context;
this.images = images;
this.something = new ArrayList<String>(something);
}
You can send what all you want to send and get it from the constructor.
I try to add search list form City list using my base adapter but it doesn't work. I want to search City in cities list. Here's My code.
My CitySerach :
private ProgressDialog pDialog;
EditText inputSearch;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// Hashmap for ListView
ArrayList<HashMap<String, String>> CitiesLI = new ArrayList<HashMap<String, String>>();
// url to make request
private static String url_cityli = "http://10.0.2.2/Myweb/ecities.php";
// JSON Keys
public static final String TAG_CITEMS_LI = "cities_li";
public static final String TAG_CID_LI = "city_id";
public static final String TAG_CNAME_LI = "city_name";
public static final String TAG_CIMG_LI = "image";
JSONArray cities_li = null;
ListView list;
CitySearchAdapter adapter;
private CitySearch activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tt);
CitiesLI = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.city_list);
//list click to details view of the place
list.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String cid_li = ((TextView) view.findViewById(R.id.cid_li)).getText().toString();
Intent i = new Intent(getApplicationContext(),
//Tab.class);
CityInfoActivity.class);
// Starting new intent
i.putExtra(TAG_CID_LI, cid_li);
startActivity(i);
//startActivityForResult(i, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new CitySearchAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CitySearch.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(url_cityli, "GET",
params);
Log.d("All Products: ", json.toString());
// looping through All data
try {
cities_li = json;
for (int i = 0; i < cities_li.length(); i++) {
JSONObject c = cities_li.getJSONObject(i);
// Storing each json item in variable
String city_id = c.getString(TAG_CID_LI);
String city_name =c.getString(TAG_CNAME_LI);
String image = c.getString(TAG_CIMG_LI);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//JSON Object
map.put(TAG_CID_LI, city_id);
map.put(TAG_CNAME_LI,city_name);
map.put(TAG_CIMG_LI, image);
// adding HashList to ArrayList
CitiesLI.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(CitiesLI);
//
// Enabling Search Filter
CitySearchAdapter adapter;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Listview name of the class
CitySearch.this.adapter.getFilter().filter(s);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
});
}
}
}
Here my CitylistAdapter :
public class CitySearchAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CitySearchAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.te, null);
TextView city_id = (TextView) vi.findViewById(R.id.cid_li);
TextView image = (TextView) vi.findViewById(R.id.cimg_li);
TextView city_name = (TextView) vi.findViewById(R.id.cname);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.cimage);
HashMap<String, String> city_li = new HashMap<String, String>();
city_li = data.get(position);
city_id.setText(city_li.get(CityActivity.TAG_CID_LI));
image.setText(city_li.get(CityActivity.TAG_CIMG_LI));
city_name.setText(city_li.get(CityActivity.TAG_CNAME_LI));
imageLoader.DisplayImage(city_li.get(CityActivity.TAG_CIMG_LI),thumb_image);
return vi;
}
public Object getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Pleace Help me.
Thanks all
I need help passing data and position from OnClickListener to a new activity. Below are my attempt. I cant seem to figure it out. Please assist. Thanks
Main
public class MainActivity extends Activity {
JSONObject json;
JSONArray jsonarray;
ListView listview;
ProgressDialog pDialog;
ListViewAdapter adapter;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "id";
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_main);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
arraylist = new ArrayList<HashMap<String, String>>();
json = JSONfunctions
.getJSONfromURL("http://www.site.com");
try {
jsonarray = json.getJSONArray("worldpopulation");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("rank", json.getString("rank"));
map.put("country", json.getString("country"));
map.put("population", json.getString("population"));
map.put("flag", json.getString("flag"));
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
listview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(MainActivity.this, arraylist);
listview.setAdapter(adapter);
//setListAdapter(adapter);
pDialog.dismiss();
Adapter Class
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
DownloadImageTask mTask;
ImageLoader imageLoader;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylistview) {
this.context = context;
data = arraylistview;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
HashMap<String, String> result = new HashMap<String, String>();
result = data.get(position);
rank = (TextView) itemView.findViewById(R.id.rank); // title
country = (TextView) itemView.findViewById(R.id.country); // title
population = (TextView) itemView.findViewById(R.id.population); // artist
flag = (ImageView) itemView.findViewById(R.id.flag); // artist
rank.setText(result.get(MainActivity.RANK));
country.setText(result.get(MainActivity.COUNTRY));
population.setText(result.get(MainActivity.POPULATION));
imageLoader.DisplayImage(result.get(MainActivity.FLAG), flag);
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, SingleItemView.class);
intent.putExtra(MainActivity.RANK);
intent.putExtra(COUNTRY, country);
intent.putExtra(POPULATION, population);
intent.putExtra(FLAG, flag);
context.startActivity(intent);
}
});
return itemView;
}
}
SingleItemView
public class SingleItemView extends Activity {
// Declare Variables
TextView txtrank;
TextView txtcountry;
TextView txtpopulation;
ImageView imgflag;
String rank;
String country;
String population;
String flag;
int position;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.singleitemview);
Intent i = getIntent();
position = i.getExtras().getInt("position");
rank = i.getStringExtra("rank");
country = i.getStringExtra("country");
population = i.getStringExtra("population");
flag = i.getStringExtra("flag");
txtrank = (TextView) findViewById(R.id.rank);
txtcountry = (TextView) findViewById(R.id.country);
txtpopulation = (TextView) findViewById(R.id.population);
txtrank.setText(rank);
txtcountry.setText(country);
txtpopulation.setText(flag);
//imgflag.setImageResource(flag);
}
I cant figure out this part intent.putExtra(MainActivity.RANK); it
needs 2 strings and also passing the position
putExtra() takes two arguments, because you have to pass in a value and a name.
You can do this to pass data:
intent.putExtra("Name", value);
Edit:
How do you pass the position too?
What position? Your adapter only provides the View for each list row. If you want to get the position of the item in a ListView (or whatever) you have to set an onItemClickListener to your ListView.
can you do this in onClick:
intent.putExtra(MainActivity.RANK,rank.getText());
In my ListView there are 2 TextViews and an ImageView.
I am using a LazyAdapter to load images from JSON file according to this link.
I am successfully loading data but i am facing the problem that each list item shows in both TextViews the link of the image while the image itself is shown correctly.
Here is the adapter:
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item, null);
TextView name = (TextView)vi.findViewById(R.id.name);
TextView price = (TextView)vi.findViewById(R.id.price);
ImageView image=(ImageView)vi.findViewById(R.id.image);
HashMap<String, String> smart = new HashMap<String, String>();
smart = data.get(position);
id.setText(smart.get(SmActivity.KEY_ID));
name.setText(smart.get(SmActivity.KEY_NAME));
price.setText(smart.get(SmActivity.KEY_PRICE));
imageLoader.DisplayImage(smart.get(SmActivity.KEY_THUMB), image);
return vi;
}
}
And here is the activity:
public class SmActivity extends ListActivity {
static String url = "url-php to get json";
public static String KEY_PRICE, KEY_NAME, KEY_THUMB;
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> smList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJson(url);
try {
JSONArray smJArray = json.getJSONArray("sm");
for(int i = 0; i < smJArray.length(); i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObj = smJArray.getJSONObject(i);
map.put(KEY_NAME, jsonObj.getString("product_name"));
map.put(KEY_PRICE, jsonObj.getString("price")+"€");
map.put(KEY_THUMB, jsonObj.getString("image_main"));
smList.add(map);
}
}
catch (JSONException e) {
e.printStackTrace();
}
list = (ListView)getListView().findViewById(android.R.id.list);
adapter=new LazyAdapter(this, smList);
list.setAdapter(adapter);
}
}
I can understand that ListView shows at all items the value of the last map.put(...) i am using.
For example, if the last put in HashMap is map.put(KEY_PRICE, jsonObj.getString("price")+"€");
i get the price value not only on price, but on name TextView as well. And of course i get no image.
I would be grateful in any help.
Thanks in advance.
Ok. i got it. i replaced:
public static String KEY_PRICE, KEY_NAME, KEY_THUMB;
by
static final String KEY_NAME = "product_name";
static final String KEY_PRICE = "price";
and
map.put("product_name", jsonObj.getString(KEY_NAME));
map.put("price", jsonObj.getString(KEY_PRICE));