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.^-^
Related
I have a spinner that gets populated from a text file stored on a web server. The contents of this text file are then stored in an ArrayList. My app is going to have the user add an item to this text file that they name themselves and therefore update the spinner. What I need to be able to do is have the spinner do something when an item is selected. As the user can give any name to an item they add, how can my app do something when that particular item is selected from the spinner if it doesn't know what they named it?
Right now I have my app set up so that if spinner item equals "string" do this... but this obviously won't work if the user has named an item themselves. I hope I have explained my question ok! This is my code so far:
public class MainActivity extends AppCompatActivity {
String statusLink = "http://redacted.uk/pmt/status.txt";
String deviceLink = "http://redacted.uk/pmt/devices.txt";
String status;
final String degree = "\u00b0";
ArrayList<String> devicesAL = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
// Set up connection to device.txt on web server
URL deviceUrl = new URL (deviceLink);
URLConnection deviceConn = deviceUrl.openConnection();
deviceConn.setDoOutput(true);
deviceConn.connect();
InputStream dis = deviceConn.getInputStream();
InputStreamReader disr = new InputStreamReader(dis, "UTF-8");
BufferedReader dbr = new BufferedReader(disr);
String deviceLine;
// Set up connection to status.txt on web server
URL statusUrl = new URL(statusLink);
URLConnection statusConn = statusUrl.openConnection();
statusConn.setDoOutput(true);
statusConn.connect();
InputStream sis = statusConn.getInputStream();
InputStreamReader sisr = new InputStreamReader(sis, "UTF-8");
BufferedReader sbr = new BufferedReader(sisr);
String statusLine;
try {
while ((deviceLine = dbr.readLine()) != null) {
//System.out.println(deviceLine);
devicesAL.add(deviceLine);
for (String str : devicesAL) {
System.out.println(str);
}
}
while ((statusLine = sbr.readLine()) != null) {
System.out.println(statusLine);
status = statusLine;
System.out.println("Status = " + status);
TextView output = (TextView) findViewById(R.id.textView);
System.out.println(status);
}
for (String str : devicesAL) {
System.out.println(str);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
//LOAD SPINNER
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter adp = new ArrayAdapter(MainActivity.this, android.R.layout.simple_spinner_item, devicesAL);
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adp);
adp.notifyDataSetChanged();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
TextView output = (TextView) findViewById(R.id.textView);
if (parent.getItemAtPosition(position).equals("Water Cooler")) {
System.out.println("Water cooler selected");
output.setText(status);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
});
} finally {
sbr.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
Since you say you want to :
If the user then selects "fridge" from the spinner, the data inside fridge.txt gets displayed
So i think you can just get the file name from the spinner then show the content. It will be like this :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedFileName = parent.getItemAtPosition(position);
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard, selectedFileName+".txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {}
TextView tvText = (TextView)findViewById(R.id.tvText);
tvText.setText(text.toString());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
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());
private class BackTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
// i want to use httppost in this ligne
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); // close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 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("ERROR", "Error converting result " + e.toString());
}
// parse json data
try {
result = result.substring(result.indexOf("["));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Prog2 p = new Prog2();
p.setTitre_emission(json_data.getString("titre_emission"));
p.setDesc_emission(json_data.getString("desc_emission"));
p.setHeure_emission(json_data.getString("heure_emission"));
p.setChaine_emission(json_data.getString("titre_chaine"));
records.add(p);
}
}
catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null)
pd.dismiss(); // close dialog
Log.e("size", records.size() + "");
adapter.notifyDataSetChanged(); // notify the ListView to get new
// records
}
}
How can I get a text from onItemListener and use it in an other function for getting an httpost?
When I use getText() I get an error
public class Wataneya1Activity extends AppCompatActivity {
Toolbar mToolbar;
Spinner mSpinner;
String text;
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter1 adapter;
ListView listProg;
ArrayList<Prog1> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wataneya1);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ImageButton mButton = (ImageButton) findViewById(R.id.Button03);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Wataneya1Activity.this.finish();
}
});
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
final ActionBar actionBar = getSupportActionBar();
mSpinner = (Spinner) findViewById(R.id.spinner_rss);
String[] items = getResources().getStringArray(R.array.days_array);
List<String> spinnerItems = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
spinnerItems.add(items[i]);
}
SpinnerAdapter adapter1 = new SpinnerAdapter(actionBar.getThemedContext(), spinnerItems);
mSpinner.setAdapter(adapter1);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) {
text = mSpinner.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
context = this;
records = new ArrayList<Prog1>();
listProg = (ListView) findViewById(R.id.prog_list);
adapter = new CustomAdapter1(context, R.layout.list_item, R.id.titre_emission, records);
listProg.setAdapter(adapter);
}
public HttpPost fnt (String text) {
if (text.equals("Mardi")) {
httppost = new HttpPost("http://192.168.:8080/TuniTV/prog_wataneya1_mardi.php");
} else if (text.equals("Mercredi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_mercredi.php");
} else if (text.equals("Jeudi")) {
httppost = new HttpPost("http://192.168/TuniTV/prog_wataneya1_jeudi.php");
} else if (text.equals("Vendredi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_vendredi.php");
} else if (text.equals("Samedi")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_samedi.php");
} else if (text.equals("Dimanche")) {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_dimanche.php");
} else {
httppost = new HttpPost("http://192.168:8080/TuniTV/prog_wataneya1_lundi.php");
}
return httppost;
}
You receive the click position ( == index into your data) in the callback method. Use it to find the data in your data array.
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int arg2, long arg3) {
text = spinnerItems.get(arg3);
Toast.makeText(getApplicationContext(), text,
Toast.LENGTH_SHORT).show();
}
Btw... Telling us there is a mistake - is crap.
Telling us what kind of mistake it is or even showing some stacktrace? Great stuff.
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.
I am fetching data from database to list view having content and an Button(Text to speech)conversion.In my listview that button is showing properly and the clickable function is also working audio is not coming,the text to speech audio function is not working properly.
Mainactivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor.getCount()>0)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
//lv1 =(ListView)findViewById(R.id.list);
//lv =(ListView)findViewById(R.id.list);
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
/*mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor.getCount()>0)
{
fillData(projectsCursor);
}*/
for(int i=0; i<ID.size(); i++){
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(ID.get(i),TITLE.get(i),CONTENT.get(i),COUNT.get(i)));
}
Dialog.dismiss();
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
}
public void getData() {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://192.168.1.18:3000/api/v1/posts.json");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i("................",_response);
httpclient.getConnectionManager().shutdown();
JSONObject jsonObject = new JSONObject(_response);
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("count");
ID.add(id);
TITLE.add(title);
CONTENT.add(content);
COUNT.add(count);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
tts = new TextToSpeech(this, this);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View arg1, int position, long id) {
if(arg1.getId()== R.id.btnaudioprayer && arg1.isClickable() ){
btnaudioprayer = (ImageButton) findViewById(R.id.btnaudioprayer);
txtText = (EditText) findViewById(R.id.text1);
Toast.makeText(MainActivity.this,txtText .getText().toString(),Toast.LENGTH_SHORT).show();
speakOut();
}
}
});
}else
{
Log.i("...........","null");
}
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit1(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnaudioprayer.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
I followed this link for text to speech http://www.androidhive.info/2012/01/android-text-to-speech-tutorial/ i download the source code its working nice,while using that code in my listview,that function is not working properly.