However, when i just check the user-defined array parameter, customerList in the outer class there are values inside but the uploadAsyncTask innerclass keeps failing on the emulator (displaying unfortunately the app has failed).
private ArrayList<CustomerData> customerList = new ArrayList<CustomerData>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
presidents = getResources().getStringArray(R.array.presidents_array);
client = new AsyncHttpClient();
Button btn_Save, btn_Backup;
btn_Save = (Button) findViewById(R.id.btnSave);
btn_Backup = (Button) findViewById(R.id.btnBackup);
txt_AcctNum = (TextView) findViewById(R.id.txtAcctNum);
txt_AcctName = (TextView) findViewById(R.id.txtAcctName);
s1 = (Spinner) findViewById(R.id.spinner);
txt_Amt = (TextView) findViewById(R.id.txtAmt);
/*
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, presidents);
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, presidents);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
//Toast.makeText(getBaseContext(),
// "You have selected item : " + presidents[index],
// Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
-------other codes here----
btn_Backup.setOnClickListener(new Button.OnClickListener() {
#SuppressWarnings(value = "unchecked")
public void onClick(View view) {
ArrayList<CustomerData> custList = new ArrayList<CustomerData>();
// db = new DBAdapter(context);
db.open();
//db.backupToSD();
//---get all contacts---
Cursor c = db.getAllCustomers();
if (c.moveToFirst()) {
do {
//DisplayContact(c);
//sendData();
custList = addAndDisplayCustomer(c);
} while (c.moveToNext());
}
/* for (int i = 0; i < custList.size(); i++) {
Toast.makeText(getApplicationContext(), "---Customer Data--- " + "id: " +
custList.get(i).getId() + " Acct Name: " +
custList.get(i).getAcctName() + " Acct Num: " +
custList.get(i).getAcctNum() + " Tnx type: " +
custList.get(i).getTxnType() + " Amt: " +
custList.get(i).getAmt(), Toast.LENGTH_LONG).show(); }*/
Toast.makeText(getApplicationContext(), " Uploading data ... " + custList.get(0).getId(), Toast.LENGTH_LONG).show();
UploadASyncTask upload = new UploadASyncTask();
upload.execute(custList);
}
public ArrayList<CustomerData> addAndDisplayCustomer(Cursor c)
{
CustomerData customer = new CustomerData(c.getString(0), c.getString(1),
c.getString(2), c.getString(3), c.getString(4));
customerList.add(customer);
return customerList;
}
//int delRows = db.deleteAll();
//db.backupToSD();
//db.dropTable();
//Toast.makeText(getApplicationContext(), " Table successfully dropped ! ", Toast.LENGTH_LONG).show();
//db.close();
});
}
private class UploadASyncTask extends AsyncTask<ArrayList<CustomerData>, Void, Void> {
private Cursor c;
private String id;
private String acct_Name ;
private String acct_Num;
private String txnType;
private String amt;
//private ArrayList<CustomerData> custList;
private Context mContext1;
private ProgressDialog dialog = null;
private Context mContext = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle(" Sending to the server... ");
dialog.setMessage("Please wait...");
dialog.setProgressDrawable(mContext.getWallpaper());
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();
}
#Override
#SafeVarargs
final protected Void doInBackground(ArrayList<CustomerData>... custList) {
try {
ArrayList<CustomerData> custom = custList[0];
for (int i = 0; i<custom.size(); i++) {
String id = custom.get(i).getId();
String acct_Name = custom.get(i).getAcctName();
String acct_Num = custom.get(i).getAcctNum();
String txnType = custom.get(i).getTxnType();
String amt = custom.get(i).getAmt();
/*runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Welcome guy: " + id,
Toast.LENGTH_LONG).show();
}
});*/
HttpParams params = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost
("http://10.0.2.2:8080/RestWebService/rest/customer");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("id", id));
postParams.add(new BasicNameValuePair("acct_name", acct_Name));
postParams.add(new BasicNameValuePair("acct_num", acct_Num));
postParams.add(new BasicNameValuePair("txn_type", txnType));
postParams.add(new BasicNameValuePair("amt", amt));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
String result = "";
id = "";
acct_Name = "";
acct_Num = "";
txnType = "";
amt = "";
}
}
catch (Exception e)
{
Log.e("Server Error: ",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//custList.clear();
dialog.dismiss();
}
}
}
When I saw your code : there is a little problem. I don't know it's the good answer but :
private Context mContext = null;
and
dialog.setProgressDrawable(mContext.getWallpaper());
It's a nullPointerException in this line
For me You can delete the context and the cursor on your AsyncTask. Create a constructor on your AsyncTask and put the context in parameters, use it for the progressDialog
Hope it's help
Related
I'm having trouble using the value of a variable in a local class and passing it to another class that will be loaded in the intent.
The string value is null and gives an error in the application.
public class Carro extends AppCompatActivity {
ListView lvCarrinhoItems;
Button bFinalizar;
String url2 = "";
String parametros2 = "";
String insertUrl = "http://localhost/registrar.php";
RequestQueue requestQueue;
String result = "";
public static String idOrder = "", dta = "";
public static MeuPedido meuPedido;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_carrinho);
lvCarrinhoItems = (ListView) findViewById(R.id.tela5lv);
LayoutInflater layoutInflater = getLayoutInflater();
final Carrinhos carrinhos = CarrinhoHelper.getCarrinhos();
final TextView tvTotalPrice = (TextView) findViewById(R.id.tvsoma);
final TextView tvObspedido = (TextView) findViewById(R.id.etobscar);
tvTotalPrice.setText((Bandeja.MOEDA+String.valueOf(carrinhos.getTotalPrice().setScale(2, BigDecimal.ROUND_HALF_UP))).replace(".",","));
final TCartItemAdapter tcartItemAdapter = new TCartItemAdapter(this);
tcartItemAdapter.updateCartItems(getCarrinhoItems(carrinhos));
lvCarrinhoItems.setAdapter(tcartItemAdapter);
bFinalizar = (Button) findViewById(R.id.button4);
bFinalizar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alerta = new AlertDialog.Builder(Carro.this);
alerta.setTitle("Confirmação de pedido");
alerta
.setIcon(R.drawable.service)
.setMessage("Deseja confirmar o seu pedido?")
.setCancelable(false)
.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
pref = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
final String idcliente = pref.getString("idusuario", null);
final String idrestaurante = CarrinhoHelper.getIdResta();
final String valorpedido = String.valueOf(carrinhos.getTotalPrice());
final String obspedido = tvObspedido.getText().toString();
if (idcliente == null){
Intent intent = new Intent(Carro.this, A2_1semlogin.class);
startActivity(intent);
}else
if (networkInfo != null && networkInfo.isConnected()) {
url2 = "http://localhost/registrarpedido.php";
parametros2 = "idcliente=" + idcliente + "&idrestaurante=" + idrestaurante + "&valorpedido=" + valorpedido + "&obspedido=" + obspedido;
new SolicitaDados2().execute(url2);
} else {
Toast.makeText(getApplicationContext(), "Por favor, verifique sua conexão", Toast.LENGTH_LONG).show();
}
Log.d("DadosRet2", parametros2);
Log.d("DadosRet2", idcliente + ", " + idrestaurante + ", " + valorpedido + ", " + obspedido);
class MyAsyncTaskresources extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
InputStream isr = null;
try{
String URL=params[0];
java.net.URL url = new URL( URL);
URLConnection urlConnection = url.openConnection();
isr = new BufferedInputStream(urlConnection.getInputStream());
}
catch(Exception e){
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
final JSONObject json = jArray.getJSONObject(i);
s = s + "login info : " + json.getString("idOrder") + " " + json.getString("idcliente") + " " + json.getString("idrestaurante") + " " + json.getString("data");
**STRING QUE DESEJO ACESSAR = idOrder**
idOrder = json.getString("idOrder");
dta = json.getString("data");
List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
Log.d(TAG, "Current shopping cart: " + carrinhos);
Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();
for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
final CarrinhoItem carrinhoItem = new CarrinhoItem();
carrinhoItem.setBandeja((Bandeja) entry.getKey());
carrinhoItem.setQuantidade(entry.getValue());
carrinhoItems.add(carrinhoItem);
final String idcomida = carrinhoItem.getBandeja().getIdcomida();
final String quantidade = carrinhoItem.getBandeja().getQuantidade();
final BigDecimal valorunit = carrinhoItem.getBandeja().getPreco();
final String adicional = carrinhoItem.getBandeja().getAdicional();
final String obsproduto = carrinhoItem.getBandeja().getObsproduto();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("idOrder",idOrder);
parameters.put("idcomida", idcomida);
parameters.put("quantidade", quantidade);
parameters.put("valorunit", valorunit.toString());
parameters.put("adicional", adicional);
parameters.put("obsproduto", obsproduto);
final MeuPedido meupedido = new MeuPedido();
String novaId = idOrder;
meupedido.setmPedido(novaId);
return parameters;
}
};
requestQueue.add(request);
}
break;
}
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
}
new MyAsyncTaskresources().execute("http://localhost/sel.php?idcliente="+idcliente+"&idrestaurante=" +idrestaurante);
}
});
AlertDialog alertaDialog = alerta.create();
alertaDialog.show();
}
});
}
public static final List<CarrinhoItem> getCarrinhoItems(Carrinhos carrinhos) {
List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
Log.d(TAG, "Current shopping cart: " + carrinhos);
Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();
for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
final CarrinhoItem carrinhoItem = new CarrinhoItem();
carrinhoItem.setBandeja((Bandeja) entry.getKey());
carrinhoItem.setQuantidade(entry.getValue());
carrinhoItems.add(carrinhoItem);
final String comida = carrinhoItem.getBandeja().getComida();
final String adicional = carrinhoItem.getBandeja().getAdicional();
final String quantidade = carrinhoItem.getBandeja().getQuantidade();
final BigDecimal valor = carrinhoItem.getBandeja().getPreco();
}
return carrinhoItems;
}
private class SolicitaDados2 extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametros2);
}
#Override
protected void onPostExecute(String resultado) {
if (resultado.contains("pedido_ok")) {
Toast.makeText(getApplicationContext(), "Registro efetuado com sucesso", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Carro.this, Anotafiscal.class);
** LOCAL ONDE DESEJO INSERIR A STRING**
String hjhj = idOrder ;
intent.putExtra("iddopedido",hjhj);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Ocorreu um erro no cadastro", Toast.LENGTH_LONG).show();
}
}
}
}
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'm using this code to fetch some data from PHP file and extract some data into my android application.
This code extract name, price and availability for each product and put each one in an String.
Now I need to have array of the product in java which that is included name,price and availability for each product and name them product1 product2 product3 so I'll be able to write rest of my code based on that.
How can I do that ?
public class MainActivity extends Activity {
private String jsonResult;
private String url = "xxxx/get_all_products.php";
private ListView listView;
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static final String TAG_FOUND = "found";
private static final String TAG_DESCRIPTION = "description";
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView1);
productList = new ArrayList<HashMap<String, String>>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selval = ((TextView) view.findViewById(R.id.name)).getText().toString();
String selval1 = ((TextView) view.findViewById(R.id.price)).getText().toString();
String selval2 = ((TextView) view.findViewById(R.id.found)).getText().toString();
// Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
// TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
// String keyword = txt.getText().toString();
Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
intnt.putExtra("selval", selval);
intnt.putExtra("selval1", selval1);
intnt.putExtra("selval2", selval2);
startActivity(intnt);
}
});
accessWebService();
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[]{url});
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("name");
String price = jsonChildNode.optString("price");
String found = jsonChildNode.optString("found");
// String outPut = name + "-" + number;
// String outPut = name + "-" + price + "-" + found;
// productList.add(createProduct("products", outPut));
HashMap<String, String> product = new HashMap<String, String>();
product.put(TAG_NAME, name);
product.put(TAG_FOUND, found);
product.put(TAG_PRICE, price);
productList.add(product);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
TAG_FOUND }, new int[] { R.id.name,
R.id.price, R.id.found });
listView.setAdapter(simpleAdapter);
}
}
its very simple, by using this code outside of the for loop
JSONObject pro1 = jsonMainNode.getJSONObject(0);
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.^-^