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());
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.
here i am displaying 1 listview which is coming from server.if i click on any item i want some alertbox to open...but for that i need match the condition eg.if listitem string matches with "Bianca pizza" then open alertbox else toast "hello"..here in my code its not taking listview item string .
its weird its taking 1st value of listview item in toast (the code which i put before if condition just to check whether its correct or not.)but when i am comparing its not working.
like in toast i m getting "Bianca pizza" but when i want to compare it with "Bianca Pizza" it should match and go inside the if condition but its not going inside and showing else condition.
here is my code:
public class SubMenu extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "id";
static String COUNTRY = "name";
private ProgressDialog pDialog;
String status="";
static String FLAG = "image";
Integer i = 1;
String _stringVal;
private static String url_create_book = "http://cloud....com/broccoli/creatinfo.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String SelectedId = getIntent().getStringExtra("id");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Get the view from listview_main.xml
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// Create a progressdialog
// mProgressDialog = new ProgressDialog(SubMenu.this);
// Set progressdialog title
// mProgressDialog.setTitle("Categories of Main categories.....");
// 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
jsonarray = JsonFunctions
.getJSONfromURL("http://cloud....com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
try {
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("name", jsonobject.getString("name"));
map.put("image", jsonobject.getString("image"));
// 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.list1);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(SubMenu.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
TextView name = (TextView) parent.findViewById(R.id.type1);
Toast.makeText(SubMenu.this, "this is "+name.getText(), Toast.LENGTH_SHORT).show();
if ( name.getText().toString().equalsIgnoreCase("Bianca Pizza"))
{
//open alertbox
}
else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
here is my listview adapter:
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 id;
TextView name;
TextView population;
CircleImageView image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.list_item1, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
// id = (TextView) itemView.findViewById(R.id.idq);
name = (TextView) itemView.findViewById(R.id.type1);
// Locate the ImageView in listview_item.xml
image = (CircleImageView) itemView.findViewById(R.id.subimg);
// icon = (ImageView) itemView.findViewById(R.id.arrow);
// Capture position and set results to the TextViews
// id.setText(resultp.get(SubMenu.RANK));
name.setText(resultp.get(SubMenu.COUNTRY));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), image);
// imageLoader.DisplayImage(resultp.get(SubMenu.FLAG), icon);
// Capture ListView item click
/**itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank", resultp.get(MainActivity.RANK));
// Pass all data country
intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
// Pass all data flag
intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});*/
return itemView;
}
}
The problem is that you used parent ! parent is the whole adapter view and it contains lots of rows in which there is a Textview with id `R.id.type1. When you use parent, it find the first item with that id in its hierarchy. That's why it always return first item.
you should do this :
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
// TextView name = (TextView) parent.findViewById(R.id.type1); WRONG
TextView name = (TextView) view.findViewById(R.id.type1);
Toast.makeText(SubMenu.this, "this is "+name.getText(), Toast.LENGTH_SHORT).show();
if ( name.getText().toString().equalsIgnoreCase("Bianca Pizza"))
{
//open alertbox
}
else {
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
}
The only change you would need to do is Use view instead of parent on onItemClick, please refer below - This will get the clicked item text directly.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long rowId) {
TextView name = (TextView) view.findViewById(R.id.type1);
Toast.makeText(SubMenu.this, "this is "+name.getText(), Toast.LENGTH_SHORT).show();
if ( name.getText().toString().equals("Bianca Pizza"))
{
//open alertbox
}
else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
I think this helpful for you.
Firstly you close DownloadJSON class before on item click then call onitem click function.
private class DownloadJSON extends AsyncTask<Void, Void, Void> implements
AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
// #Override
// protected void onPreExecute() {
// super.onPreExecute();
// Create a progressdialog
// mProgressDialog = new ProgressDialog(SubMenu.this);
// Set progressdialog title
// mProgressDialog.setTitle("Categories of Main categories.....");
// 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
jsonarray = JsonFunctions
.getJSONfromURL("http://cloud....com/broccoli/menu_typeitem.php?id=" + getIntent().getStringExtra("id"));
try {
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
map.put("name", jsonobject.getString("name"));
map.put("image", jsonobject.getString("image"));
// 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.list1);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(SubMenu.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
}
}
In if condition write this.
if( name.getText().toString().equals("Bianca Pizza")){
}else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
or
if( name.getText().toString().matches("Bianca Pizza")){
}else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
MainFragment:
public class MainFragment extends Fragment {
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String COUNTRY = "country";
static String POPULATION = "population";
static String FLAG = "flag";
// URL Address
String url = "http://";
public MainFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.activity_main, container, false);
new JsoupListView().execute();
return view;
}
// Title AsyncTask
private class JsoupListView extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Diziler Yükleniyor");
// Set progressdialog message
mProgressDialog.setMessage("Yükleniyor...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Connect to the Website URL
Document doc = Jsoup.connect(url).get();
// Identify Table Class "worldpopulation"
for (Element table : doc.select("div[class=col-sm-12 col-xs-12 pad0 middle]")) {
// Identify all the table row's(tr)
for (Element row : table.select("div[class=col-sm-12 col-xs-12 pad0 streamingBoxWrap mNewsItem]:gt(0)")) {
HashMap<String, String> map = new HashMap<String, String>();
// Identify all the table cell's(td)
Elements tds = row.select("a");
// Identify all img src's
Elements imgSrc = row.select("img[src]");
// Get only src from img src
String imgSrcStr = imgSrc.attr("src");
Elements aSrc = row.select("a[href]:gt(1)");
String aSrcStr = aSrc.attr("href");
// Retrive Jsoup Elements
// Get the first td
map.put("rank", aSrcStr);
// Get the second td
map.put("country", tds.get(1).text());
// Get the third td
map.put("population", tds.get(2).text());
// Get the image src links
map.put("flag", imgSrcStr);
// Set all extracted Jsoup Elements into the array
arraylist.add(map);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Locate the listview in listview_main.xml
listview = (ListView) getActivity().findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(getActivity(), arraylist);
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
ListViewAdapter:
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 rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.singleitemview, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainFragment.RANK));
country.setText(resultp.get(MainFragment.COUNTRY));
population.setText(resultp.get(MainFragment.POPULATION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainFragment.FLAG), flag);
// Capture ListView item click
return itemView;
}
}
Error:
at
omer.s.MainFragment$JsoupListView.onPostExecute(MainFragment.java:125)
at
omer.s.MainFragment$JsoupListView.onPostExecute(MainFragment.java:55)
MainFragment.java:125:
listview.setAdapter(adapter);
MainFragment.java:55:
private class JsoupListView extends AsyncTask<Void, Void, Void> {
The problem is you are looking up the ListView in the host Activity layout but you probably want the ListView from the Fragment layout.
Update the onCreateView(...) method to:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.activity_main, container, false);
listview = (ListView) view.findViewById(R.id.listview);
new JsoupListView().execute();
return view;
}
and then remove listview = (ListView) getActivity().findViewById(R.id.listview); from onPostExecute() since you already have a reference to the listview you want.
I have this 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 NAME = "rank";
static String TYPE = "country";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.activity_main);
// 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 = JSONParser
.getJSONfromURL("http://54.218.73.244:7002/");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
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(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
//map.put(MainActivity.FLAG, jsonobject.getString("restaurantIMAGE"));
// 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();
}
}
}
ListViewAdapter.java:
public abstract 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 rank;
TextView country;
//ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// Locate the ImageView in listview_item.xml
//flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
rank.setText(resultp.get(MainActivity.NAME));
country.setText(resultp.get(MainActivity.TYPE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
// imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("name", resultp.get(MainActivity.NAME));
// Pass all data country
intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
// intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
And it gives an Error:
Cannot instantiate the type ListAdapter
Why am i getting this error? A little help would be appreciated.
I believe that you should initialize you list view in the onCreate() of your activity. Maybe you could try that.
your listadapter is an abstract class that is why you r getting the error make that class public
Trying to update rating value obtained from JSON to rating bar
I achieved updating value to textvie but ............ How to update the value from JSON rating to rating bar
These are the classes i have used
MainActivity.java
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
static String PRICE= "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// 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("Fetching the information");
// 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("url");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("restaurants");
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(MainActivity.NAME, jsonobject.getString("restaurantNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("restaurantTYPE"));
map.put(MainActivity.FLAG, "http://54.218.73.244:7005/"+jsonobject.getString("restaurantIMAGE"));
map.put(MainActivity.DISTANCE, jsonobject.getString("restaurantDISTANCE"));
map.put(MainActivity.RATING, jsonobject.getString("restaurantRATING"));
map.put(MainActivity.PRICE, jsonobject.getString("restaurantPrice"));
// 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) {
// 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();
}
}
}
ListViewAdapter.java
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 name;
TextView type;
TextView distance;
TextView rating;
Button price;
ImageView flag;
RatingBar ratingbar;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.RestaurantNameID);
type = (TextView) itemView.findViewById(R.id.RestaurantTypeID);
distance = (TextView) itemView.findViewById(R.id.RestaurantDistanceID);
rating = (TextView) itemView.findViewById(R.id.RestaurantRatingID);
price=(Button) itemView.findViewById(R.id.BuyButton);
ratingbar=(RatingBar) itemView.findViewById(R.id.ratingIndicator);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
name.setText(resultp.get(MainActivity.NAME));
type.setText(resultp.get(MainActivity.TYPE));
distance.setText(resultp.get(MainActivity.DISTANCE));
rating.setText(resultp.get(MainActivity.RATING));
price.setText(resultp.get(MainActivity.PRICE));
//ratingbar.setRating(resultp.get(MainActivity.RATING));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, RestaurantDesc.class);
// Pass all data rank
intent.putExtra("REST", resultp.get(MainActivity.NAME));
// Pass all data country
//intent.putExtra("type", resultp.get(MainActivity.TYPE));
// Pass all data flag
//intent.putExtra("flag", resultp.get(MainActivity.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
listview_item.xml .
<RatingBar
android:id="#+id/ratingIndicator"
style="?android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/RestaurantPicImageLinearViewID"
android:layout_centerHorizontal="true" />
Any Ideas !
In your onPostExecute():
RatingBar ratingBar = (RatingBar)findViewById(R.id.ratingIndicator);
ratingBar.setEnabled(false);
ratingBar.setMax(5); // I assume 5 is your max rating
ratingBar.setRating(Integer.parseInt(arraylist.get(MainActivity.RATING)));