how to match string value in" if else" condition in android? - android

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("Bian‌​‌​ca 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("Bian‌​‌​ca 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("Bian‌​‌​ca 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("Bian‌​‌​ca Pizza")){
}else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}
or
if( name.getText().toString().matches("Bian‌​‌​ca Pizza")){
}else{
Toast.makeText(SubMenu.this, "hello", Toast.LENGTH_SHORT).show();
}

Related

activity shows blank result?

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.

FATAL EXCEPTION : main Android Attempt to invoke virtual method 'org.json.JSONArray a

When i run my code It displays the message Unfortunately your app has closed. This started happening after ProgressDialog dismiss.
I think the error here [Searchresult.java]
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(Searchresult.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
Here's my log cat
Shutting down VM
06-30 05:08:03.882 23680-23680/com.ali.test E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ali.test, PID: 23680
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.ali.test.Searchresult$DownloadJSON.onPostExecute(Searchresult.java:93)
at com.ali.test.Searchresult$DownloadJSON.onPostExecute(Searchresult.java:54)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
06-30 05:08:03.884 1768-2143/system_process W/ActivityManager: Force finishing activity com.ali.test/.Searchresult
home.jave [main file]
public class home extends AppCompatActivity {
EditText search_txt;
Button search_btn;
String strbook;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
search_txt = (EditText) findViewById(R.id.editText);
search_btn = (Button) findViewById(R.id.button);
search_btn.setOnClickListener(listener);
search_txt.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
search_btn.setOnClickListener(listener);
return true;
}
return false;
}
});
}private OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
strbook = search_txt.getText().toString();
if (TextUtils.isEmpty(strbook))
{
search_txt.setError("Enter name");
}
else {
Intent i = new Intent(home.this, Searchresult.class);
startActivity(i);
}
}
};
}
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 rank;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.list_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
rank = (TextView) itemView.findViewById(R.id.rank);
// 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(Searchresult.RANK));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(Searchresult.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("rank", resultp.get(Searchresult.RANK));
// Pass all data flag
intent.putExtra("flag", resultp.get(Searchresult.FLAG));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
searchresult.java
public class Searchresult extends AppCompatActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String RANK = "rank";
static String FLAG = "flag";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listview = (ListView) findViewById(R.id.list);
// Get the view from listview_main.xml
setContentView(R.layout.list_item);
// 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(Searchresult.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.androidbegin.com/tutorial/jsonparsetutorial.txt");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
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("rank", jsonobject.getString("rank"));
map.put("flag", jsonobject.getString("flag"));
// 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
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(Searchresult.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Make sure that the json returned is the one you expect. So as state before, check that you have indeed a jsonobject, then check that there is a jsonarray with the expected name, and look at the schema as well.
You can have a look at Retrofit library which is awesome for RESTful services calls. http://square.github.io/retrofit/
Has a small learning curve though.

MainFragment BaseAdapter Error

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.

ListViewAdapter not getting initialized

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

How to update the ratingbar in android

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)));

Categories

Resources