I have a custom ListView layout that I got from a website. It allows me to click on an item from a list and repopulates the same layout with a new list of different items based on the item you clicked. The layout works fine and I got it to populate with information pulled from a database.
The problem that Im having is that instead of having it repopulate the layout with a new list when clicked, I would like it to go to another layout. I tried a couple things but had no luck. Here is my code. Thank you for the help in advance:
public class firstactivity extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
CustomAdapter adapter;
int pos=1;
public int picpos = 0;
LinkedList<String> region = new LinkedList<String>();
String name = null;
String something = null;
private Integer[] imgid = {
R.drawable.icon
};
RelativeLayout layr1;
Animation ar3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
String finaline = "";
//Get info from database
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http connection
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8888/PhpProject1/index.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag"," names: "+json_data.getString("name")
);
//Get an output to the screen
finaline = "\n\t" + jArray.getJSONObject(i);
something = finaline.substring(finaline.indexOf(',',10));
name = something.substring(9,finaline.indexOf('\"', 9));
region.add(something);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
//set list with information from database
for(int i=0;i<region.size();i++){
try {
rd = new RowData(i,region.get(i));
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
adapter = new CustomAdapter(this, R.layout.second_list,R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
//getListView().setOnItemClickListener(this);
}
/*private OnClickListener SaveListener = new OnClickListener(){
public void onClick(View v){
setContentView(R.layout.newlayout);
}
};*/
/*protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
setContentView(R.layout.newlayout);
//final Intent intent = new Intent();
//startActivityForResult(intent, position);
}*/
public void onListItemClick(ListView parent, View v, int position, long id) {
adapter = (CustomAdapter) parent.getAdapter();
data.removeAllElements();
//String insert_list;
////
//if(position==0) {
/*setContentView(R.layout.newlayout);
TextView textView1 = (TextView) findViewById(R.id.textView1);
textView1.setText((String)region.get(0));*/
//setListAdapter(adapter);
//getListView().setTextFilterEnabled(true);
if(position == 0)
setContentView(R.layout.newlayout);
}
private class RowData {
protected int mId;
protected String mTitle;
RowData(int id,String title){
mId=id;
mTitle = title;
}
#Override
public String toString() {
return mId+" "+mTitle;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.second_list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
i11=holder.getImage();
i11.setImageResource(imgid[0]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
It sounds like what you are looking for is a way to go to a new Activity and display a new ListView. To go to a new Activity you would do something like:
startActivity(new Intent(this, SecondActivity.class));
This line of code is creating a new Intent object, which tells Android which Activity to open next. You are then passing that Intent to the startActivity method of your current Activity. A more detailed explanation is here: http://developer.android.com/reference/android/app/Activity.html#StartingActivities
It also might be useful for you to pass some information to the next Activity, like the name of a state which was selected. You can do that by putting this information into the Intent object:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("state", "New York");
startActivity(intent);
You can get this data from within SecondActivity by doing:
Intent incomingIntent = getIntent();
String state = incomingIntent.getExtras().getString("state");
SecondActivity refers to a new class which extends Activity that you will need to define in your code. Don't forget to add it to your manifest.xml too, otherwise you will get an exception when trying to start it.
Related
In my activity I am adding a header button to save the values of a listview, with an EditText and post them to a php/mysql web app.
I am able to get the values of the listview if I use setOnItemClickListener but when I use setOnClickListener on the header save button, I am not able to iterate through the listview.
I am using a custom array adaptor :-
public class CustomOrderAdaptor extends ArrayAdapter{
int groupid;
ArrayList<OneOrder> records;
Context context;
public CustomOrderAdaptor(Context context, int vg, int id, ArrayList<OneOrder>records) {
super(context, vg, id, records);
this.context = context;
groupid = vg;
this.records = records;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(groupid, parent, false);
TextView textName = (TextView) itemView.findViewById(R.id.product_name);
textName.setText(records.get(position).getproduct_name());
EditText new_quantity = (EditText) itemView.findViewById(R.id.new_quantity);
new_quantity.setText(records.get(position).getnew_quantity());
TextView textOrderitemid = (TextView) itemView.findViewById(R.id.order_item_id);
textOrderitemid.setText(records.get(position).getorder_item_id());
TextView textQuantity = (TextView) itemView.findViewById(R.id.quantity);
textQuantity.setText(records.get(position).getquantity());
return itemView;
}
}
data model :-
public class OneOrder {
private String quantity;
private String new_quantity;
private String product_name;
private String order_item_id;
public void setquantity(String quantity){this.quantity=quantity;}
public void setnew_quantity(String new_quantity){this.new_quantity=new_quantity;}
public void setproduct_name(String product_name){this.product_name=product_name;}
public void setorder_item_id(String order_item_id){this.order_item_id=order_item_id;}
public String getquantity(){return quantity;}
public String getnew_quantity(){return new_quantity;}
public String getproduct_name(){return product_name;}
public String getorder_item_id(){return order_item_id;}
}
My activity is :-
protected void onCreate(Bundle savedInstanceState) {
//TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_order);
context = this;
records = new ArrayList<OneOrder>();
listOrder = (ListView) findViewById(R.id.order_item_list);
LayoutInflater inflater = LayoutInflater.from(this);
View nTop = inflater.inflate(R.layout.activity_get_order_footer, null);
listOrder.addHeaderView(nTop);
adapter = new CustomOrderAdaptor(context, R.layout.list_order, R.id.product_name,
records);
listOrder.setAdapter(adapter);
Button mButton = (Button) nTop.findViewById(R.id.button_save);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject order_items = new JSONObject();
JSONObject sendObject = new JSONObject();
for (int i=0;i<adapter.getCount();i++){
JSONObject order_item = new JSONObject();
OneOrder current_order = (OneOrder) listOrder.getAdapter().getItem(i);
//OneOrder current_order = (OneOrder) getListView().getItemAtPosition(i);
try {
order_item.put("quantity", current_order.getquantity().toString());
order_item.put("new_quantity", current_order.getnew_quantity().toString());
order_item.put("order_item_id", current_order.getorder_item_id().toString());
order_items.put(String.valueOf(i),order_item);
} catch (JSONException e) {
e.printStackTrace();
}
}
HttpURLConnection conn = null;
try {
Intent i = getIntent(); // gets the previously created intent
String order_id = i.getStringExtra("order_id");
sendObject.put("items", order_items.toString());
sendObject.put("order_id", order_id);
try {
URL url = new URL("http://192.168.0.70/steam_dos/index.php?option=com_steam§ion=linen&task=save_order_out");
String message = sendObject.toString();
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( 10000 /*milliseconds*/ );
conn.setConnectTimeout( 15000 /* milliseconds */ );
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setFixedLengthStreamingMode(message.getBytes().length);
//make some HTTP header nicety
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//open
conn.connect();
//setup send
BufferedOutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(message.getBytes());
//clean up
os.flush();
//do something with response
InputStream is = conn.getInputStream();
}catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
the error is here :-
order_item.put("quantity", current_order.getquantity().toString());
the error is simple :-
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String au.com.southportsteamlaundry.rfid.steamscanadditions.OneOrder.getquantity()' on a null object reference
The view looks like this :-
Layout view
I am trying to save all of the values of the listview after the save button is clicked but I am not getting the listview items with that code, could you please explain the best way to achieve that ? Thanks.
Normally it's not recommended to use Edit text with adapter, the reason is edit text saving cannot be handled when it scroll out.
There are two kinds solution.
Replace the listview with scrollview
2 create a variable and add a TextWatcher on the edittext. Whenever the edittext get modified, the text watcher detect the change and override the variable whener you done something on it.
code would be like
Implementing Text Watcher for EditText
my answer may not be the best one, but this is what I implemented to get the EditText values of the list view :
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONObject order_item = new JSONObject();
order_items_edited = new JSONObject();
for (int i = 0; i < listOrder.getCount(); i++) {
EditText et = (EditText) listOrder.getChildAt(i).findViewById(R.id.new_quantity);
if (et!=null) {
TextView oi = (TextView) listOrder.getChildAt(i).findViewById(R.id.order_item_id);
Log.i("dtag", "et is " + String.valueOf(et.getText()));
Log.i("dtag", "oi is " + String.valueOf(oi.getText()));
try {
order_item.put("new_quantity", String.valueOf(et.getText()));
order_item.put("order_item_id", String.valueOf(oi.getText()));
order_items_edited.put(String.valueOf(i),order_item);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
the main issue I was having was a null object for et, which is valid, but I wasn't testing for it.
Now its working, I will look at implementing a cleaner solution.
i am trying to send Data (ID value) from one activity to other
but it wouldn't send correct data , i want it to send only ID Value of Clicked Item to next activity , here is my code
public class Order extends AppCompatActivity {
private ListView lvUsers;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sub);
dialog = new ProgressDialog(this);
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.setMessage("Loading, please wait.....");
lvUsers = (ListView) findViewById(R.id.lvUsers);
new JSONTask().execute("http://146.185.178.83/resttest/order");
}
public class JSONTask extends AsyncTask<String, String, List<OrderModel> > {
#Override
protected void onPreExecute(){
super.onPreExecute();
dialog.show();
}
#Override
protected List<OrderModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line=reader.readLine()) !=null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONArray parentArray = new JSONArray(finalJson);
List<OrderModel> orderModelList = new ArrayList<>();
Gson gson = new Gson();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
OrderModel orderModel = gson.fromJson(finalObject.toString(), OrderModel.class);
orderModelList.add(orderModel);
}
return orderModelList;
}catch (MalformedURLException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null) {
connection.disconnect();
}
try {
if (reader !=null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<OrderModel> result) {
super.onPostExecute(result);
dialog.dismiss();
OrderAdapter adapter = new OrderAdapter(getApplicationContext(), R.layout.row_order, result);
lvUsers.setAdapter(adapter);
}
}
public class OrderAdapter extends ArrayAdapter {
public List<OrderModel> orderModelList;
private int resource;
private LayoutInflater inflater;
public OrderAdapter(Context context, int resource, List<OrderModel> objects) {
super(context, resource, objects);
orderModelList = 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(resource, null);
holder.bOrderNo = (Button) convertView.findViewById(R.id.bOrderNo);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
final int orderId = orderModelList.get(position).getId();
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderId);
startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
private Button bOrderNo;
}
}
}
The holder gets executed in loop i guess is why it wouldn't send right Id.
How do i get it to send only Id of the clicked orderId
you can check this link to see how json Response looks like http://146.185.178.83/resttest/order
You have a silly mistake in your code . I have edited single line in your code . I think you are getting same "orderId" every time instead of actual "orderId". Check this one . I hope your problem will resolve .
final int index = position;
holder.bOrderNo.setText("Order No: " + orderModelList.get(position).getOrderId());
holder.bOrderNo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Order.this, OrderSelected.class);
intent.putExtra("parameter_name", orderModelList.get(index).getId());
startActivity(intent);
}
});
Please try
In place of
intent.putExtra("parameter_name", orderId);
Please put
intent.putExtra("parameter_name", orderModelList.get(position).getId());
I'm trying to populate an ArrayList of objects and use those objects to populate a ListView. My Asynctask can get the json data and I can parse it and make the objects I need but my ListView doesn't populate. When I check to see if my ArrayList has any object in it before the adapter runs I can see that it doesn't. I want to know why my ListView isn't populating.
Here's my code: (Sorry if it's messy, some spots I haven't gotten to updating yet)
public class MovieDisplayFragment extends Fragment{
private ArrayList<Movie> movieList = new ArrayList<Movie>();
private MovieAdapter movieAdapter;
ListView listView;
public MovieDisplayFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
movieAdapter = new MovieAdapter(getActivity(), movieList);
listView = (ListView) rootView.findViewById(R.id.listview_data);
listView.setAdapter(movieAdapter);
if(movieList.size() > 0) {
Log.e("Hello", "1");
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l){
Movie movie = movieAdapter.getItem(position);
Intent i = new Intent(getActivity(), DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT, "Hello");
startActivity(i);
}
});
return rootView;
}
private void updateMovieData(){
getMovieData movieData = new getMovieData();
movieData.execute();
}
#Override
public void onStart(){
super.onStart();
updateMovieData();
}
public class getMovieData extends AsyncTask<Void, Void, List<Movie>> {
private final String LOG_CAT = getMovieData.class.getSimpleName();
private List<Movie> getMovieData(String movieJsonStr) throws JSONException {
final String MOV_ITEMS = "results";
final String MOV_TITLE = "original_title";
final String MOV_DATE = "release_date";
final String MOV_SYNOPSIS = "overview";
final String MOV_VOTE = "vote_average";
final String MOV_POSTER_URL = "poster_path";
JSONObject movieJson = new JSONObject(movieJsonStr);
JSONArray movieArray = movieJson.getJSONArray(MOV_ITEMS);
Log.e("Hello", "2");
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movie = movieArray.getJSONObject(i);
movieList.add(new Movie(movie.getString(MOV_TITLE), movie.getString(MOV_DATE),
movie.getString(MOV_SYNOPSIS), movie.getString(MOV_VOTE), movie.getString(MOV_POSTER_URL)));
}
return movieList;
}
protected List<Movie> doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String movieJsonStr = null;
try {
final String BASE_URL = "http://api.themoviedb.org/3/genre/10751/movies?api_key=358f3b44734f7e6404f2d01a62d3c176&include_all_movies=true&include_adult=true";
Uri builtUri = Uri.parse(BASE_URL).buildUpon().build();
URL url = new URL(builtUri.toString());
Log.v(LOG_CAT, "Built URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null){
movieJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while((line = reader.readLine()) != null){
buffer.append(line + "\n");
}
if (buffer.length() == 0){
movieJsonStr = buffer.toString();
}
movieJsonStr = buffer.toString();
Log.v(LOG_CAT, "Movie String: " + movieJsonStr);
} catch (IOException e) {
Log.e("Fragment", "Error", e);
movieJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
return getMovieData(movieJsonStr);
} catch (JSONException e) {
Log.e(LOG_CAT, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<Movie> movies){
if(movies != null){
movieAdapter.clear();
for(Movie movieData : movies){
movieAdapter.add(movieData);
}
}
}
}
}
Put these 2 lines inside your onPostExecute() in Async.
movieAdapter = new MovieAdapter(getActivity(), movieList);
listView.setAdapter(movieAdapter);
AsyncTask runs in Background Thread. It gets the data from json after few seconds. But your adapter is called few milli seconds after your fragment is created.
So the data from the Json will not be there when you are setting the adapter.
Calling it in onPostExecute solves this problem as the adatpter is set after Json data is retrieved from the server!
Hope it helps a bit.
You are printing size of movieList (movieList.size()) much before movieList() is getting populated. It will never print "Hello" "1" in debugger. The asynctask will fill data in movieList much later than your movieList.size() check code in OnCreateView()
Anyways, after the below code
for(Movie movieData : movies)
{
movieAdapter.add(movieData);
}
you need to insert this bit:
listView.setAdapter(movieAdapter);
You are populating the adapter but not setting it to your listView in your onPostExecute() in your getMovieData Asynctask.
It looks like on post execute you are clearing the List that your adapter is using to populate the listview, then adding in new items to the list. However, in order to update the view after that happens, you need to call notifyDataSetChanged(); after updating the list
#Override
protected void onPostExecute(List<Movie> movies){
if(movies != null){
movieAdapter.clear();
for(Movie movieData : movies){
movieAdapter.add(movieData);
}
movieAdapter.notifyDataSetChanged();
}
}
I have an async task which populates a spinner with data. The spinner data comes from objects in a list. My problem is when I set the onclick listener for the items in the list I also want the id from the object not just the name:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
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();
}
}
This line below is the line which get the beers name, but I do not know how to get also the id from the object which sets the listview name:
String portfolioChoice = portfolioType.getSelectedItem().toString();
Update:
I have changed my above code to this to incorporate a custom adapter:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
//tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
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();
}
}
but on this line:
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
I am getting shortbeerinfoadapter does not have type parameters
my short beer info adapter is:
public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo> {
Context context;
int layoutResourceId;
List<ShortBeerInfo> data = null;
public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> 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.txtBeer = (TextView)row.findViewById(R.id.breweryName);
holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
ShortBeerInfo beer = data.get(position);
holder.txtBeer.setText(beer.beer);
holder.txtRate.setText(beer.rate + " out of 5.00 Stars");
holder.numHolder= Float.parseFloat(beer.rate);
holder.txtBar.setNumStars(5);
holder.txtBar.setRating(holder.numHolder);
return row;
}
static class beerHolder
{
TextView txtBeer;
TextView txtRate;
RatingBar txtBar;
Float numHolder;
}
}
You have your ShortBeerInfo, which includes the name and ID. You take the beer name, add it to a list of strings, then create the ArrayAdapter from that list. The ArrayAdapter only contains the names.
To get the ID you will need a custom array adapter of type ShortBeerInfo. You'll need to override OnCreateView in the adapter to create the View object for the list item that only contains the beer name. (Or any other beer info you may want to display)
Then in your selection listener getSelectedItem will return a ShortBeerInfo, containing the ID of the selected beer.
Hi I am writting an android application to get information from a url and show it in a ListView. All are working well. but it takes long time to show the View because i read the file from url on onCreate() method.
I want read from the URL asynchronously, so view response time will not harmed.
Am I using the ProgressBar correctly?.
public class cseWatch extends Activity {
TextView txt1 ;
Button btnBack;
ListView listView1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchresult);
Button btnBack=(Button) findViewById(R.id.btn_bck);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent MyIntent1 = new Intent(v.getContext(),cseWatchMain.class);
startActivity(MyIntent1);
}
});
ArrayList<SearchResults> searchResults = GetSearchResults();
//after loaded result hide progress bar
ProgressBar pb = (ProgressBar) findViewById(R.id.progressBar1);
pb.setVisibility(View.INVISIBLE);
final ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}//end of onCreate
private ArrayList<SearchResults> GetSearchResults(){
ArrayList<SearchResults> results = new ArrayList<SearchResults>();
SearchResults sr;
InputStream in;
try{
txt1 = (TextView) findViewById(R.id.txtDisplay);
txt1.setText("Sending request...");
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.myurl?reportType=CSV");
HttpResponse response = httpclient.execute(httpget);
in = response.getEntity().getContent();
txt1.setText("parsing CSV...");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line;
reader.readLine(); //IGNORE FIRST LINE
while ((line = reader.readLine()) != null) {
String[] RowData = line.split(",");
sr = new SearchResults();
String precent = String.format("%.2g%n",Double.parseDouble(RowData[12])).trim();
double chng=Double.parseDouble(RowData[11]);
String c;
if(chng > 0){
sr.setLine2Color(Color.GREEN);
c="▲";
}else if(chng < 0){
sr.setLine2Color(Color.rgb(255, 0, 14));
c="▼";
}else{
sr.setLine2Color(Color.rgb(2, 159, 223));
c="-";
}
sr.setName(c+RowData[2]+"-"+RowData[1]);
DecimalFormat fmt = new DecimalFormat("###,###,###,###.##");
String price = fmt.format(Double.parseDouble(RowData[6])).trim();
String tradevol = fmt.format(Double.parseDouble(RowData[8])).trim();
sr.setLine1("PRICE: Rs."+price+" TRADE VOL:"+tradevol);
sr.setLine2("CHANGE:"+c+RowData[11]+" ("+precent+"%)");
results.add(sr);
txt1.setText("Loaded...");
// do something with "data" and "value"
}
}
catch (IOException ex) {
Log.i("Error:IO",ex.getMessage());
}
finally {
try {
in.close();
}
catch (IOException e) {
Log.i("Error:Close",e.getMessage());
}
}
}catch(Exception e){
Log.i("Error:",e.getMessage());
new AlertDialog.Builder(cseWatch.this).setTitle("Watch out!").setMessage(e.getMessage()).setNeutralButton("Close", null).show();
}
return results;
}
}
AsyncTask should be used to move the heavylifting away from UI thread. http://developer.android.com/reference/android/os/AsyncTask.html
I think you should use a runable.
demo code:
final ListView lv = (ListView) findViewById(R.id.listView1);
Handler handler = new Handler(app.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(new MyCustomBaseAdapter(cseWatch.this, searchResults));
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv.getItemAtPosition(position);
SearchResults fullObject = (SearchResults)o;
Toast.makeText(cseWatch.this, "You have chosen: " + " " + fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
}, 1000);
try it.^-^