Constructor undefined in custom adapter - android

I made a custom adapter following this tutorial here:
http://www.ezzylearning.com/tutorial.aspx?tid=1763429
I changed my custom adapter to match my classes and need to look like this:
package com.example.beerportfoliopro;
public class BeerSearchAdapter extends ArrayAdapter<BeerData>{
Context context;
int layoutResourceId;
BeerData data[] = null;
public BeerSearchAdapter(Context context, int layoutResourceId, BeerData[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data[position];
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
The error I am getting when I try and call my adapter is:
The constructor BeerSearchAdapter(Search, int, List<BeerData>) is undefined
I am calling the adapter with:
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(Search.this ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
My full Search.java is:
package com.example.beerportfoliopro;
public class Search extends Activity implements OnQueryTextListener {
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("logIN", "starting activity");
setContentView(R.layout.activity_search);
}
#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);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setOnQueryTextListener(this);
return true;
}
//get entered search and pop up a toast to show query entered
public boolean onQueryTextSubmit (String query) {
//toast query
Toast.makeText(this, "Searching for: " + query + "...", Toast.LENGTH_SHORT).show();
//make json variables to fill
// url to make request
String url = "http://api.brewerydb.com/v2/search?key=myKey&format=json&type=beer&withBreweries=y&q=";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult().execute(jsonUrl);
return false;
}
private class ReadJSONResult extends AsyncTask
<String, Void, String> {
protected String doInBackground(String... urls) {
return readJSONFeed(urls[0]);
}
protected void onPostExecute(String result) {
try {
//start progress bar
//requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
//setProgressBarIndeterminateVisibility(true);
///get
JSONObject json = new JSONObject(result);
//acces listview
lv = (ListView) findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(Search.this ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Intent i = new Intent(Search.this, BeerPage.class);
BeerData beerInfo = beerList.get(arg2);
//Toast.makeText(MainActivity.this, beerInfo.beerName, Toast.LENGTH_SHORT).show();
i.putExtra("myBeerObject", beerInfo);
i.setClass(Search.this, BeerPage.class);
startActivity(i);
}
});
//end progress bar
//setProgressBarIndeterminateVisibility(false);
} catch (Exception e) {
Log.d("ReadBeerDataTask", e.getLocalizedMessage());
}
}
}
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//gets the json from the inputed url
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
}

Based on the error, beerList is apparently a List<BeerData>. Your constructor does not take a List<BeerData>. It takes a BeerData[]. Convert your adapter's constructor to take a List<BeerData> instead.

You can use this instead
BeerSearchAdapter adapter1 = new BeerSearchAdapter(Search.this
,R.layout.listview_item_row, (BeerData[])beerList.toArray());
lv.setAdapter(adapter1);

That will be undefine because you declare your constructor as this
BeerSearchAdapter(Context context, int layoutResourceId, BeerData[] data)

Related

Populate data into listview using json parsom with restful api

I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..
if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html
Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}

Why does this URL-JSON Parsing code not working when I Extract the tags but works when I extract the entire array?

When I try to parse the entire array it works but Instead when I try to parse the array element like ID, t, l etc. from the URL, the code doesn't work.
Kindly explain in detail, as I'm a rookie :)
PS: I believe the entire data in the form of Strings. Like: "l" : "219.20".
The URL is as follows :
http://finance.google.com/finance/info?q=BSE:SBIN
and the other resources are as follows :
MainActivity.java
public class MainActivity extends AppCompatActivity {
public String theUrl;
public String stockName;
ListView lvStock;
HttpURLConnection connection;
URL url;
InputStream inputStream;
BufferedReader bufferedReader;
StringBuffer stringBuffer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvStock = (ListView) findViewById(R.id.lvStocks);
stockName = "SBIN";
theUrl = "http://finance.google.com/finance/info?q=BSE:" + stockName;
Toast.makeText(MainActivity.this, "You have selected : " + stockName, Toast.LENGTH_SHORT).show();
}
public class RefreshStock extends AsyncTask<String, String, List<StockModel>> {
#Override
protected List<StockModel> doInBackground(String... params) {
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null)
stringBuffer.append(line + "\n");
String data = stringBuffer.toString();
return parseJSON(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private List<StockModel> parseJSON(String json) {
List<StockModel> stockModelList = new ArrayList<>();
//Using it to remove the two forward slashes in the json online.
json = json.substring(2);
try {
StockModel stockModel = new StockModel();
JSONObject parentObject = new JSONObject();
JSONArray jsonArray = parentObject.getJSONArray(json);
JSONObject childObject = jsonArray.getJSONObject(0);
String stockId = childObject.getString("id");
String stockName = childObject.getString("t");
String stockRate = childObject.getString("l");
String stockChange = childObject.getString("c");
String stockChangePercent = childObject.getString("cp");
stockModel.setId(stockId);
stockModel.setT(stockName);
stockModel.setL(stockRate);
stockModel.setC(stockChange);
stockModel.setCp(stockChangePercent);
stockModelList.add(stockModel);
return stockModelList;
} catch (JSONException e) {
e.printStackTrace();
}
return stockModelList;
}
protected void onPostExecute(List<StockModel> result) {
super.onPostExecute(result);
//Toast.makeText(getApplicationContext(), new StringBuilder().append("").append(result.toString()).toString(), Toast.LENGTH_LONG).show();
StockAdapter adapter = new StockAdapter(getApplicationContext(), R.layout.listrow, result);
lvStock.setAdapter(adapter);
}
}
public class StockAdapter extends ArrayAdapter {
private List<StockModel> stockModelList;
private int resource;
private LayoutInflater inflater;
private StockAdapter(Context context, int resource, List<StockModel> objects) {
super(context, resource, objects);
stockModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.listrow, null);
holder.stockID = (TextView) convertView.findViewById(R.id.txtStockID);
holder.stockName = (TextView) convertView.findViewById(R.id.txtStockName);
holder.stockRate = (TextView) convertView.findViewById(R.id.txtStockRate);
holder.stockChange = (TextView) convertView.findViewById(R.id.txtStockChange);
holder.stockChangePercent = (TextView) convertView.findViewById(R.id.txtStockChangePercent);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.stockID.setText(stockModelList.get(position).getId());
holder.stockName.setText(stockModelList.get(position).getT());
holder.stockRate.setText(stockModelList.get(position).getL());
holder.stockChange.setText(stockModelList.get(position).getC());
holder.stockChangePercent.setText(stockModelList.get(position).getCp());
return convertView;
}
}
private class ViewHolder {
private TextView stockRate;
private TextView stockChangePercent;
private TextView stockChange;
private TextView stockName;
private TextView stockID;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
new RefreshStock().execute(theUrl);
return true;
}
return super.onOptionsItemSelected(item);
}
}
and the other class is as follows :
package org.example.km.http2json.Models;
public class StockModel {
private String id;
private String t;
//private String e;
private String l;
//private String l_fix;
//private String l_cur;
//private String s;
//private String ltt;
//private String lt;
//private String llt_dts;
private String c;
//private String c_fix;
private String cp;
//private String cp_fix;
//private String ccol;
//private String pcls_fix;
public String getId(){
return id;
}
public void setId(String id){
this.id = id;
}
public String getT(){
return t;
}
public void setT(String t){
this.t = t;
}
public String getL(){
return l;
}
public void setL(String l){
this.l = l;
}
public String getC(){
return c;
}
public void setC(String c){
this.c = c;
}
public String getCp(){
return cp;
}
public void setCp(String cp){
this.cp = cp;
}
}
/*
// [
{
"id": "13564339"
,"t" : "SBIN"
,"e" : "NSE"
,"l" : "219.20" // Last Value
,"l_fix" : "219.20"
,"l_cur" : "Rs.219.20"
,"s": "0"
,"ltt":"3:56PM GMT+5:30"
,"lt" : "Jul 1, 3:56PM GMT+5:30"
,"lt_dts" : "2016-07-01T15:56:11Z"
,"c" : "+0.40" //Change
,"c_fix" : "0.40"
,"cp" : "0.18" //Change Percent
,"cp_fix" : "0.18"
,"ccol" : "chg"
,"pcls_fix" : "218.8" // Previous Closing
}
]
*/
// there is no data your parsing.. please check
JSONArray jsonArray = parentObject.getJSONArray("");
JSONObject childObject = jsonArray.getJSONObject(0);
String stockId = childObject.getString("id");
String stockName = childObject.getString("t");
String stockRate = childObject.getString("l");
String stockChange = childObject.getString("c");
String stockChangePercent = childObject.getString("cp");
note : below data will throw parser exception, remove first two frontslash chars
// [ { "id": "13564339" ,"t" : "SBIN" ,"e" : "NSE" ,"l" : "219.20" ,"l_fix" : "219.20" ,"l_cur" : "Rs.219.20" ,"s": "0" ,"ltt":"3:56PM GMT+5:30" ,"lt" : "Jul 1, 3:56PM GMT+5:30" ,"lt_dts" : "2016-07-01T15:56:11Z" ,"c" : "+0.40" ,"c_fix" : "0.40" ,"cp" : "0.18" ,"cp_fix" : "0.18" ,"ccol" : "chg" ,"pcls_fix" : "218.8" } ]
I have updated the RefreshStock file
public class RefreshStock extends AsyncTask<String, String, List<StockModel>> {
#Override
protected List<StockModel> doInBackground(String... params) {
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
inputStream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null)
stringBuffer.append(line + "\n");
String data = stringBuffer.toString();
return parseJSON(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
private List<StockModel> parseJSON(String json) {
List<StockModel> stockModelList = new ArrayList<>();
try {
StockModel stockModel = new StockModel();
JSONObject parentObject = new JSONObject();
JSONArray jsonArray = parentObject.getJSONArray(json);
JSONObject childObject = jsonArray.getJSONObject(0);
String stockId = childObject.getString("id");
String stockName = childObject.getString("t");
String stockRate = childObject.getString("l");
String stockChange = childObject.getString("c");
String stockChangePercent = childObject.getString("cp");
stockModel.setId(stockId);
stockModel.setT(stockName);
stockModel.setL(stockRate);
stockModel.setC(stockChange);
stockModel.setCp(stockChangePercent);
stockModelList.add(stockModel);
return stockModelList;
} catch (JSONException e) {
e.printStackTrace();
}
return stockModelList;
}
protected void onPostExecute(List<StockModel> result) {
super.onPostExecute(result);
//Toast.makeText(getApplicationContext(), new StringBuilder().append("").append(result.toString()).toString(), Toast.LENGTH_LONG).show();
StockAdapter adapter = new StockAdapter(getApplicationContext(), R.layout.listrow, result);
lvStock.setAdapter(adapter);
}
}

ListView Empty When Poputaing

I am trying to add items from database onto a listView, when I use System.out.println I see values but upon trying to populate them onto a custom listview returns no data in the listview.
When launching the app, I get a single row of listview item but of course it's empty.
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
String jsonResult;
String url = "http://www.mywebsite/query.php";
ListView list;
List<String> arrName;
List<String> arrNumber;
List<String> arrUsername;
List<String> arrStatus;
String name;
String number;
String username;
String status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
arrName = Arrays.asList(name);
arrNumber = Arrays.asList(number);
arrUsername = Arrays.asList(username);
arrStatus = Arrays.asList(status);
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { //SINGLE CLICK
// TODO Auto-generated method stub
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
class ContactsAdapter extends ArrayAdapter<String>
{
Context context;
List<String> Name;
List<String> Number;
List<String> Username;
List<String> Status;
ContactsAdapter(Context c, List<String> Name, List<String> Number, List<String> Username, List<String> Status)
{
super(c, R.layout.activity_contacts_single, R.id.textName, Name);
this.context=c;
this.Name=Name;
this.Number=Number;
this.Username=Username;
this.Status=Status;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=convertView;
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.activity_contacts_single, parent, false);
}
TextView txtName = (TextView) row.findViewById(R.id.textName);
TextView txtNumber = (TextView) row.findViewById(R.id.textNumber);
TextView txtUsername = (TextView) row.findViewById(R.id.textUsername);
TextView txtStatus = (TextView) row.findViewById(R.id.textStatus);
txtName.setText(Name.get(position));
txtNumber.setText(Number.get(position));
txtUsername.setText(Username.get(position));
txtStatus.setText(Status.get(position));
return row;
}
}
}
It's because you haven't add those items into your lists, Change this part of your code:
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("main");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.getString("Name");
number = jsonChildNode.getString("Number");
username = jsonChildNode.getString("Username");
status = jsonChildNode.getString("Status");
//add this part to your code
arrName.add(name);
arrNumber.add(number);
arrUsername.add(username);
arrStatus.add(status);
System.out.println("Name: "+name);
System.out.println("Number: "+number);
System.out.println("Username: "+username);
System.out.println("Status: "+status);
}
} catch (JSONException e) {
Log.i("Error Log: ", e.toString());
System.out.println("Error: "+e.toString());
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
ContactsAdapter adapter = new ContactsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
for your second problem I think you can change your code this way:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
//arrName = Arrays.asList(name);
//arrNumber = Arrays.asList(number);
//arrUsername = Arrays.asList(username);
//arrStatus = Arrays.asList(status);
arrName = new ArrayList<String>();
arrNumber =new ArrayList<String>();
arrUsername =new ArrayList<String>();
arrStatus =new ArrayList<String>();
list = (ListView) findViewById(R.id.listContacts);
ConatctsAdapter adapter = new ConatctsAdapter(this, arrName, arrNumber, arrUsername, arrStatus);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
accessWebService();
}

android-amazing-listview, how Can I update the new page load by passing data to the URL

On the auto load, I need to be able to load more items from the URL. Where I am getting my Data via Json.
in my API call class I need to add to this nuber 10 as:
pairs.add(new BasicNameValuePair("limit", "10"));
Whenever the list view finish loading the currently data, then changes the value above and check again.
I though I needed to create a method in PaginationDemoActivity where it check for if more pages, then use intent to pass a new variable to overwrite ("limit", "10")) in the JSONfunctions class
Any advice ? Thanks guys
JSONfunctions
public class JSONfunctions extends Activity{
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
//Add URL Encoding by sending post data
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("c","getlist"));
pairs.add(new BasicNameValuePair("page","1"));
pairs.add(new BasicNameValuePair("limit", "10"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
httppost.setEntity(entity);
// end Add URL Encoding by sending post data
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
//end test
/*
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// Convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Data
public class Data {
static String URL = " my api url";
static String itemsPerPage = "20";
public static final String TAG = Data.class.getSimpleName();
public static List<Pair<String, List<Composer>>> getAllData() {
List<Pair<String, List<Composer>>> res = new ArrayList<Pair<String, List<Composer>>>();
for (int i = 0; i < 4; i++) {
res.add(getOneSection(i));
}
return res;
}
public static List<Composer> getFlattenedData() {
List<HashMap<String, String>> arraylist;
JSONObject jsonobject;
JSONArray jsonarray;
List<Composer> res = new ArrayList<Composer>();
//Pair<String, List<Composer>> mydata;
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL(URL);
Log.e("check", jsonobject.toString());
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("data");
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("id", jsonobject.getString("id"));
map.put("title", jsonobject.getString("title"));
map.put("s_desc", jsonobject.getString("s_desc"));
map.put("img", jsonobject.getString("img"));
// Set the JSON Objects into the array
arraylist.add(map);
Composer s = new Composer(
jsonobject.getString("title"),
jsonobject.getString("s_desc"),
jsonobject.getString("id"),
jsonobject.getString("img"));
res.add(s);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return res;
}
protected void updateUrlItems()
{
}
public static Pair<Boolean, List<Composer>> getRows(int page) {
List<Composer> flattenedData = getFlattenedData();
if (page == 1) {
return new Pair<Boolean, List<Composer>>(true, flattenedData.subList(0, 5));
} else {
SystemClock.sleep(2000); // simulate loading
return new Pair<Boolean, List<Composer>>(page * 5 < flattenedData.size(),
flattenedData.subList((page - 1) * 5, Math.min(page * 5, flattenedData.size())));
}
}
public static Pair<String, List<Composer>> getOneSection(int index) {
String[] titles = {"", "", "", ""};
Composer[][] composerss = {
{
new Composer("", "", "", ""),
},
};
return new Pair<String, List<Composer>>(titles[index], Arrays.asList(composerss[index]));
}
}
PaginationDemoActivity
public class PaginationDemoActivity extends Activity {
AmazingListView lsComposer;
PaginationComposerAdapter adapter;
ImageLoader imageLoader;
// Flag for current page
static Integer current_page = 10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pagination_demo);
imageLoader = new ImageLoader(this);
lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
lsComposer.setAdapter(adapter = new PaginationComposerAdapter());
adapter.notifyMayHaveMorePages();
}
public void bRefresh_click(View v) {
adapter.reset();
adapter.resetPage();
adapter.notifyMayHaveMorePages();
}
class PaginationComposerAdapter extends AmazingAdapter {
List<Composer> list = Data.getRows(1).second;
private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;
public void reset() {
if (backgroundTask != null) backgroundTask.cancel(false);
list = Data.getRows(1).second;
notifyDataSetChanged();
}
#Override
public int getCount() {
return list.size();
}
#Override
public Composer getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
protected void onNextPageRequested(int page) {
Log.d(TAG, "Got onNextPageRequested page=" + page);
if (backgroundTask != null) {
backgroundTask.cancel(false);
}
backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
#Override
protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
int page = params[0];
Log.e("more page", "page: " + page);
return Data.getRows(page);
}
#Override
protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
if (isCancelled()) return;
Log.e("onPostExecute", "result: " + result.first);
list.addAll(result.second);
nextPage();
notifyDataSetChanged();
if (result.first) {
// still have more pages
notifyMayHaveMorePages();
} else {
notifyNoMorePages();
}
};
}.execute(page);
}
#Override
protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {
}
#Override
public View getAmazingView(int position, View convertView, ViewGroup parent) {
View res = convertView;
if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);
// we don't have headers, so hide it
res.findViewById(R.id.header).setVisibility(View.GONE);
TextView lName = (TextView) res.findViewById(R.id.lName);
TextView lYear = (TextView) res.findViewById(R.id.lYear);
TextView lId = (TextView) res.findViewById(R.id.lId);
// Locate the ImageView in listview_item.xml
ImageView lImg = (ImageView) res.findViewById(R.id.lImg);
Composer composer = getItem(position);
lName.setText(composer.name);
lYear.setText(composer.year);
lId.setText(composer.id);
Log.e("getAmazingView PRINT THE URL 1111111111", "URL: " + composer.img);
// Capture position and set results to the ImageView
// Passes img images URL into ImageLoader.class
imageLoader.DisplayImage(composer.img, lImg);
Log.e("222","333");
//khen
lsComposer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// TODO Auto-generated method stub
if(id > -1){
Composer composer = adapter.getItem(position);
Intent intent = new Intent();
intent.setClass(getApplicationContext(), SingleItemView.class);
Bundle bundle = new Bundle();
bundle.putString("id", composer.id);
bundle.putString("name", composer.name);
bundle.putString("year", composer.year);
bundle.putString("img", composer.img);
intent.putExtras(bundle);
startActivity(intent);
}
}
});
//end khen
return res;
}
#Override
public void configurePinnedHeader(View header, int position, int alpha) {
}
#Override
public int getPositionForSection(int section) {
return 0;
}
#Override
public int getSectionForPosition(int position) {
return 0;
}
#Override
public Object[] getSections() {
return null;
}
}
}

NullPointerException while using asyncTask, interface, and fragments

I have an async task that loads a list view of items. I am currently trying to set the onClick to load a new fragment with an "id" that is being retrieved from the list item that is clicked. I have no errors in my code that the Android Studio shows me.
When I run the app and click on the item in the list view I get this FC:
02-13 19:49:56.813 20334-20334/com.beerportfolio.beerportfoliopro E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.beerportfolio.beerportfoliopro.ReadJSONResult$1.onItemClick(ReadJSONResult.java:140)
at android.widget.AdapterView.performItemClick(AdapterView.java:298)
at android.widget.AbsListView.performItemClick(AbsListView.java:1237)
at android.widget.ListView.performItemClick(ListView.java:4555)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3037)
at android.widget.AbsListView$1.run(AbsListView.java:3724)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:5789)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:843)
at dalvik.system.NativeStart.main(Native Method)
02-13 19:50:42.112 20864-20870/? E/jdwp﹕ Failed sending reply to debugger: Broken pipe
line 140 in ReadJSONResult is:
listenerBeer.onArticleSelected(idToSend);
That line is part of this whole onClick:
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
All the code for ReadJSONResult is:
public class ReadJSONResult extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
public ReadJSONResult(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
//code for on click
OnArticleSelectedListener listenerBeer;
public interface OnArticleSelectedListener{
public void onArticleSelected(String myString);
}
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
//end code for onClick
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Searching Beer Cellar");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(android.R.id.list);
//make array list for beer
final List<BeerData> beerList = new ArrayList<BeerData>();
//get json items
for(int i = 0; i < json.getJSONArray("data").length(); i++) {
String beerId = GetBeerDataFromJSON(i,"id", json);
String beerName = GetBeerDataFromJSON(i,"name", json);
String beerDescription = GetBeerDataFromJSON(i,"description" , json);
String beerAbv = GetBeerDataFromJSON(i,"abv" , json);
String beerIbu = GetBeerDataFromJSON(i,"ibu" , json);
String beerIcon = GetBeerIconsFromJSON(i, "icon",json );
String beerMediumIcon = GetBeerIconsFromJSON(i, "medium",json );
String beerLargeIcon = GetBeerIconsFromJSON(i, "large",json );
String beerGlass = GetBeerGlassFromJSON(i, json );
String beerStyle = GetBeerStyleFromJSON(i,"name", json );
String beerStyleDescription = GetBeerStyleFromJSON(i,"description", json );
String beerBreweryId = GetBeerBreweryInfoFromJSON(i, "id", json );
String beerBreweryName = GetBeerBreweryInfoFromJSON(i, "name", json );
String beerBreweryDescription = GetBeerBreweryInfoFromJSON(i, "description", json );
String beerBreweryWebsite = GetBeerBreweryInfoFromJSON(i, "website", json );
//get long and latt
String beerBreweryLat = GetBeerBreweryLocationJSON(i, "longitude", json );
String beerBreweryLong = GetBeerBreweryLocationJSON(i, "latitude", json );
String beerBreweryYear = GetBeerBreweryInfoFromJSON(i, "established", json );
String beerBreweryIcon = GetBeerBreweryIconsFromJSON(i,"large",json);
//create beer object
BeerData thisBeer = new BeerData(beerName, beerId, beerDescription, beerAbv, beerIbu, beerIcon,
beerMediumIcon,beerLargeIcon, beerGlass, beerStyle, beerStyleDescription, beerBreweryId, beerBreweryName,
beerBreweryDescription, beerBreweryYear, beerBreweryWebsite,beerBreweryIcon, beerBreweryLat, beerBreweryLong);
//add beer to list
beerList.add(thisBeer);
}
//update listview
BeerSearchAdapter adapter1 = new BeerSearchAdapter(c ,R.layout.listview_item_row, beerList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
BeerData beerInfo = beerList.get(arg2);
String idToSend = beerInfo.beerId;
//todo: launch beer fragment
listenerBeer.onArticleSelected(idToSend);
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
//todo: all the get functions go here
private String GetBeerDataFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerBreweryIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONObject("images").getString(whatIsTheKeyYouAreLookFor);;
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get icons
private String GetBeerIconsFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("labels").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get style information
private String GetBeerStyleFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("style").getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get location data
private String GetBeerBreweryLocationJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getJSONArray("locations").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get brewery information
//get style information
private String GetBeerBreweryInfoFromJSON(int position, String whatToGet, JSONObject json ) {
String whatIsTheKeyYouAreLookFor = whatToGet;
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONArray("breweries").getJSONObject(0).getString(whatIsTheKeyYouAreLookFor);
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
//get glass
private String GetBeerGlassFromJSON(int position, JSONObject json ) {
int whereInTheJSONArrayForLoopIsTheData = position;
String holder = "";
try{
holder = json.getJSONArray("data").getJSONObject(whereInTheJSONArrayForLoopIsTheData).getJSONObject("glass").getString("name");
} catch (JSONException e) {
holder = "N/A";
}
return holder;
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
BeerSearchAdapter is:
public class BeerSearchAdapter extends ArrayAdapter<BeerData> {
Context context;
int layoutResourceId;
List<BeerData> data = null;
public BeerSearchAdapter(Context context, int layoutResourceId, List<BeerData> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBrewery = (TextView)row.findViewById(R.id.beerBreweryNameList);
holder.txtTitle = (TextView)row.findViewById(R.id.beerNameList);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
BeerData beer = data.get(position);
holder.txtTitle.setText(beer.beerName);
holder.txtBrewery.setText(beer.beerBreweryName);
return row;
}
static class beerHolder
{
TextView txtBrewery;
TextView txtTitle;
}
}
My Search.java where the interface comes form is here:
public class Search extends Fragment implements SearchView.OnQueryTextListener, ReadJSONResult.OnArticleSelectedListener {
private ListView lv;
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//set layout here
v = inflater.inflate(R.layout.activity_search, container, false);
setHasOptionsMenu(true);
getActivity().setTitle("Search");
//get user information
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//todo: code body goes here
// Inflate the layout for this fragment
return v;
}
#Override
public void onCreateOptionsMenu (Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu, inflater);
Log.d("click", "inside the on create");
//inflater.inflate(R.menu.main, menu);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search2).getActionView();
searchView.setIconified(false);
searchView.setOnQueryTextListener(this);
}
public boolean onQueryTextSubmit (String query) {
//toast query
//make json variables to fill
// url to make request
String url = "myURL";
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String jsonUrl = url + query;
//todo: get json
new ReadJSONResult(getActivity()).execute(jsonUrl);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onArticleSelected(String b){
//code to execute on click
Fragment Fragment_one;
FragmentManager man= getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
//todo: set to beer fragment
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", b);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
}
Let me know if you need any other code, I am stomped on this and could use a second pair of eyes. Thanks.
From the error message, it is obvious that listenerBeer reference is null.
I see this code:
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
But I don't see any code that calls it. Unless there is code you have not included that sets the listenerBeer reference, that would explain why it is null.
Somewhere in your code you will have to do something like this:
. . .
setOnArticleSelectedListener(new OnArticleSelectedListener() {
public void onArticleSelected(String myArticle) {
// Do something here....
}
});
. . .
HTH
You have got it correct that at the below call to onArticleSelected your listenerBeer is null.
listenerBeer.onArticleSelected(idToSend);
The only possible reason behind it is that it is not initiallized before making this call. As visible from your code the only place you are doing the initialization is in the below method.
public void setOnArticleSelectedListener(OnArticleSelectedListener listener){
this.listenerBeer = listener;
}
But, I cannot see any implementation of this. Can you do a null check before listenerBeer.onArticleSelected(idToSend); and verify if listenerBeer is initialized like
if (null != listenerBeer){
listenerBeer.onArticleSelected(idToSend);
}else{
Log.d("Null Check", "ListenereBeer is " + String.valueOf(listenerBeer));
}

Categories

Resources