how to close this progress dialog in post execute in android - android

I have made a custom progress Dialog,I wan to close it in my postExecute method,I have tried as below,But i don't know how to dismiss it.I have tried as below,Can anyone Please tell me how can i dismiss that custom dialog
main
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epe.yehki.adapter.ProductAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.uc.Menu;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class SearchActivity extends Activity {
public com.epe.yehki.uc.Menu searchMenu;
public Header searchHeader;
public EditText et_serach;
JSONObject jsonObj;
private ProgressDialog pDialog;
Intent in = null;
String searchUrl;
int flag;
public Header header;
public Menu menu;
public TextView title;
Bitmap bitmap;;
private ProductAdapter productContent;
// PRODUCTS....
// arrayLists......
public static ArrayList<String> productArray;
public static ArrayList<String> categoryArray;
ProgressBar progressBar;
//
// contacts JSONArray
JSONArray subcategories = null;
JSONArray products = null;
public String catid;
public String id;
public String pid;
String name;
ListView lv;
// Hashmap for ListView
ArrayList<HashMap<String, String>> subcategoryList;
ArrayList<HashMap<String, String>> productList;
// new
public String proname;
public String prodesc;
public String proimg;
public String proMinOrderQty;
public String proMinPrice;
public String proMaxPrice;
public String proTerms;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_search);
productList = new ArrayList<HashMap<String, String>>();
searchMenu = (com.epe.yehki.uc.Menu) findViewById(R.id.menusearch);
searchMenu.setSelectedTab(2);
searchHeader = (Header) findViewById(R.id.headersearch);
searchHeader.title.setText("Search");
et_serach = (EditText) findViewById(R.id.et_serach);
lv = (ListView) findViewById(R.id.serch_list);
productContent = new ProductAdapter(SearchActivity.this, productList);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "") != null && !Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "").equals(" ")
&& !Pref.getValue(SearchActivity.this, Const.PREF_CUSTOMER_ID, "").equals("0")) {
in = new Intent(getApplicationContext(), ProductDetailActivity.class);
proname = ((TextView) view.findViewById(R.id.product_label)).getText().toString();
// getting ProductId from the tag...
pid = productList.get(position).get(Const.TAG_PRODUCT_ID);
proimg = productList.get(position).get(Const.TAG_PRODUCT_IMG);
System.out.println(":::::::::::::::;;THE INTENT FOR THE PRODUCUT DETIALS ACTIVITY=================" + pid);
in.putExtra(Const.TAG_PRODUCT_ID, pid);
in.putExtra(Const.TAG_PRODUCT_IMG, proimg);
in.putExtra(Const.TAG_PRODUCT_NAME, proname);
startActivity(in);
} else {
in = new Intent(SearchActivity.this, LoginActivity.class);
startActivity(in);
}
}
});
et_serach.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
System.out.println(":::::::::::::::;after text changed called:::");
productList.clear();
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() != 0) {
System.out.println(":::::::::::::::;on text changed called:::");
// CALL SEARCH API........!!!
productList.clear();
new GetSearchList().execute();
}
}
});
}
public void addProgressBar(Activity activity) {
final ViewGroup rootFrameLayout = (ViewGroup) activity.getWindow().peekDecorView();
final ViewGroup modal = new RelativeLayout(activity);
progressBar = new ProgressBar(activity);
LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
((android.widget.RelativeLayout.LayoutParams) layoutParams).addRule(RelativeLayout.CENTER_IN_PARENT);
modal.addView(progressBar, layoutParams);
rootFrameLayout.addView(modal, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
rootFrameLayout.invalidate();
}
// SEARCH API()..!!!
private class GetSearchList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
productList.clear();
addProgressBar(SearchActivity.this);// pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
BackendAPIService sh = new BackendAPIService();
searchUrl = Const.API_PRODUCT + "?product_name=" + et_serach.getText().toString().trim();
System.out.println(":::::::::::::::::::SUB URL:::::::::::::::::" + searchUrl);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(searchUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.getString(Const.TAG_STATUS).equals("success")) {
if (jsonObj.has(Const.TAG_PRODUCT_DETAIL)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_PRODUCT_DETAIL));
products = jsonObj.getJSONArray(Const.TAG_PRODUCT_DETAIL);
if (products != null && products.length() != 0) {
// looping through All Contacts
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
pid = c.getString(Const.TAG_PRODUCT_ID);
System.out.println("::::::::::::::::::PARSING PRODUCT ID:::::::::::::" + pid);
String proname = c.getString(Const.TAG_PRODUCT_NAME);
String prodesc = c.getString(Const.TAG_LISTING_DESCRIPTION);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
System.out.println("::::::::::::::;products Length:::::::::::" + products.length());
System.out.println(":::::::::::::::My Image Url:::::::::::::" + proimg);
String proMinOrderQty = c.getString(Const.TAG_PRODUCT_MIN_ORDER_QTY);
c.getString(Const.TAG_PRODUCT_MIN_PRICE);
c.getString(Const.TAG_PRODUCT_MAX_PRICE);
c.getString(Const.TAG_PRODUCT_PAYMENT_TERMS);
// for company details..!!!
// new Working
HashMap<String, String> product = new HashMap<String, String>();
product.put(Const.TAG_PRODUCT_ID, pid);
product.put(Const.TAG_PRODUCT_NAME, proname);
product.put(Const.TAG_PRODUCT_IMG, proimg);
product.put(Const.TAG_PRODUCT_MIN_ORDER_QTY, proMinOrderQty);
product.put(Const.TAG_PRODUCT_DESCRIPTION, prodesc);
productList.add(product);
}
}
}
} else {
runOnUiThread(new Runnable() {
public void run() {
Utils.showCustomeAlertValidation(SearchActivity.this, "No Product found", "Yehki", "Ok");
}
});
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
productContent.notifyDataSetChanged();
lv.setAdapter(productContent);
}
}
}

Its easy try:
pDialog.dismiss();

STEP 1
Declare progress dialog above on create
private ProgressDialog pDialog;
STEP 2
Define preExecute method
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setTitle("Please wait");
pDialog.setMessage("Processing...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
pDialog.show();
}
STEP 3
//Your back ground task as it is
STEP 4
ADD postExecute Method
protected void onPostExecute()
{
pDialog.dismiss();
}

You need to just call dismiss() method for ProgressDialog. Like
protected void onPostExecute(){
pDialog.dismiss();
}

You have the progressBar variable that holds a reference to the progress bar in your layout. To hide it, call
progressBar.setVisibility(View.GONE);
The RelativeLayout you're placing the ProgressBar in is unnecessary. Also consider including the ProgressBar statically in your layout and just setting its visibility to VISIBLE/GONE as necessary.

Related

How to adapt a Spinner item to TexView

I my application insert data in database and save this data in listView. when a user click on item in listview, a this information is available to textView form. But how to adapt spinner item in textView?
package cm.mavis.crud2;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
public class TampilPegawai extends AppCompatActivity implements View.OnClickListener{
private TextView editTextId;
private Spinner spinneragence;
private TextView editTextName;
private TextView editTextDesg;
private TextView editTextSalary;
private Button buttonUpdate;
private Button buttonDelete;
private String id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tampil_pegawai);
Intent intent = getIntent();
id = intent.getStringExtra(Configuration.EMP_ID);
spinneragence = (Spinner)findViewById(R.id.spinner1);
editTextName = (TextView) findViewById(R.id.editTextName);
editTextDesg = (TextView) findViewById(R.id.editTextDesg);
editTextSalary = (TextView) findViewById(R.id.editTextSalary);
buttonUpdate = (Button) findViewById(R.id.buttonUpdate);
buttonDelete = (Button) findViewById(R.id.buttonDelete);
buttonUpdate.setOnClickListener(this);
buttonDelete.setOnClickListener(this);
getEmployee();
}
private void getEmployee(){
class GetEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilPegawai.this,"Fetching...","Patientez...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
showEmployee(s);
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Configuration.URL_GET_EMP,id);
return s;
}
}
GetEmployee ge = new GetEmployee();
ge.execute();
}
private void showEmployee(String json){
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Configuration.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String agence = c.getString(Configuration.TAG_AGENCE);
String name = c.getString(Configuration.TAG_NOM);
String desg = c.getString(Configuration.TAG_POSITION);
String sal = c.getString(Configuration.TAG_SALAIRE);
spinneragence.
editTextName.setText(name);
editTextDesg.setText(desg);
editTextSalary.setText(sal);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void updateEmployee(){
final String agence = spinneragence.getSelectedItem().toString();
final String name = editTextName.getText().toString().trim();
final String desg = editTextDesg.getText().toString().trim();
final String salary = editTextSalary.getText().toString().trim();
class UpdateEmployee extends AsyncTask<Void,Void,String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilPegawai.this,"Mise a jour...","Patientez...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(TampilPegawai.this,s,Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put(Configuration.KEY_EMP_ID,id);
hashMap.put(Configuration.KEY_EMP_NOM,name);
hashMap.put(Configuration.KEY_EMP_AGENCE,agence);
hashMap.put(Configuration.KEY_EMP_POSITION,desg);
hashMap.put(Configuration.KEY_EMP_SALAIRE,salary);
RequestHandler rh = new RequestHandler();
String s = rh.sendPostRequest(Configuration.URL_UPDATE_EMP,hashMap);
return s;
}
}
UpdateEmployee ue = new UpdateEmployee();
ue.execute();
}
private void deleteEmployee(){
class DeleteEmployee extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(TampilPegawai.this, "Mise a jour...", "Patientez...", false, false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(TampilPegawai.this, s, Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequestParam(Configuration.URL_DELETE_EMP, id);
return s;
}
}
DeleteEmployee de = new DeleteEmployee();
de.execute();
}
private void confirmDeleteEmployee(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Voulez vous supprimer ce salarié?");
alertDialogBuilder.setPositiveButton("Oui",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
deleteEmployee();
startActivity(new Intent(TampilPegawai.this,TampilSemuaPgw.class));
}
});
alertDialogBuilder.setNegativeButton("Non",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
#Override
public void onClick(View v) {
if(v == buttonUpdate){
updateEmployee();
}
if(v == buttonDelete){
confirmDeleteEmployee();
}
}
}
Please help me to rectify this code.the spinner choice is insert correctly in database but how to show this in textView form?
In Android you can style UI elements as things they are not. For example,
<style name="SpinnerText" parent="android:Widget.TextView"/>
then,
<Spinner style="#style/SpinnerText" .../>
You'll probably have to tweak that to get exactly what you are looking for, but you get the idea.

How to get specific list item and pass the two values from one activity to another?

I am developing an Android app and I in my SecondActivity I have parsed some JSON values as a listview and I want to open up ThirdActivity when a particular list item is clicked and send the values "name" and "number" to the ThirdActivity.
I have tried by creating an Intent in the OnPostExecute method. But am unable to figure out how to pass the values on to the next activity.
package com.example.acer.videoapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SecondActivity extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView listView1;
Toolbar toolbar1;
String subjectName;
ArrayList<HashMap<String, String>> lessonList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//setting title to toolbar
toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
Bundle bundle = getIntent().getExtras();
if(bundle!=null) {
toolbar1.setTitle(bundle.getString("Subject"));
subjectName=toolbar1.getTitle().toString();
}
lessonList = new ArrayList<>();
listView1 = (ListView) findViewById(R.id.list);
new GetLessons().execute();
}
/* Async task class to get json by making HTTP call */
private class GetLessons extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SecondActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = getResources().getString(R.string.lessons_url, subjectName);
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
// Getting JSON Array
JSONArray lessons = new JSONArray(jsonStr);
// looping through All lessons
for (int i = 0; i < lessons.length(); i++) {
JSONObject c = lessons.getJSONObject(i);
String number = c.getString("lessonNo");
String name = c.getString("lessonName");
// tmp hash map for single lesson
HashMap<String, String> lesson = new HashMap<>();
// adding each child node to HashMap key => value
lesson.put("number", number);
lesson.put("name", name);
// adding lesson to lesson list
lessonList.add(lesson);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Json parsing error: " + e.getMessage(),Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Couldn't get json from server. Check LogCat for possible errors!",Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SecondActivity.this, lessonList,R.layout.list_item, new String[]{"number", "name",}, new int[]{R.id.lnumber,R.id.lname});
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
//intent.putExtra("Lesson", listView1.getItemAtPosition(i).toString());
startActivity(intent);
}
});
}
}
}
Can you try this please
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
HashMap<String, String> lesson = lessonList.get(i);
intent.putExtra("number", lesson.get("number"));
intent.putExtra("name", lesson.get("name"));
startActivity(intent);
}});
Similar question has been asked before. You have most of it in place, just use Intent.PutStringArrayListExtra and then getIntent.getStringArrayListExtra to pass objects between the activities.
Check this:
Intent.putExtra List

When i click a list item i want to store it name in an edittext

I am creating an eWallet application like many existing ones. I have lots of classes that do different stuff but i need some advice in a group of them. I have created a listview witch fetches the categories i have created and saved in a phpMyAdmin database. I am displaying this data on a list view successfully. This list view just shows the list of the categories to the user and if he clicks a list item a new activity appers which llows him to edit or delete the list item.
Now i used the same code (i lterally used the same code!) to create a second listview inside a dialog box. Imagine that this listview appears inside the dialog box when i click an edit text which has an on click listener. I successfully display the data in this second list view as well. Now on this dialog box when i click a list item/category (lets say Sports category) i want the name of the edit text to change to the category i chose. But i am confused because i use the same code and methods that open the edit and delete activity on my first list view. I hope i did not confuse you too much.
Here is the code that downloads the data in my list views.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ExDownloaderActivity extends AsyncTask<Void, Integer, String>
{
Context context;
String address;
ListView expenseListView;
ProgressDialog progressDialog;
public ExDownloaderActivity(Context context, String address, ListView exCategoryListView)
{
this.context = context;
this.address = address;
this.expenseListView = exCategoryListView;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching Data...Please wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params)
{
String data = downloadData();
return data;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String string)
{
super.onPostExecute(string);
progressDialog.dismiss();
if(string != null)
{
ExParserActivity parser = new ExParserActivity(context, string, expenseListView);
parser.execute();
}
else
{
Toast.makeText(context, "Unable to download data",Toast.LENGTH_LONG).show();
}
}
private String downloadData()
{
//connect and get a stream of data
InputStream inputStream = null;
//to store each line
String line = null;
try
{
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader!= null)
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
}
else
{
return null;
}
return stringBuffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return null;
}
}
Second Class
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ExParserActivity extends AsyncTask<Void, Integer, Integer>
{
Context context;
ListView exListView;
String data;
ArrayList<String> exCategories = new ArrayList<>();
ProgressDialog progressDialog;
public ExParserActivity(Context context, String data, ListView lv)
{
this.context = context;
this.data = data;
this.exListView = lv;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing...Please wait");
progressDialog.show();
}
//Heavy job
#Override
protected Integer doInBackground(Void... params)
{
return this.parse();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
progressDialog.dismiss();
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, exCategories);
//ADAPT TO LIST VIEW
exListView.setAdapter(arrayAdapter);
//ON CLICK LISTENER
exListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
context.startActivity(new Intent(context, UpdateDeleteExCategories.class));
//Snackbar.make(view, exCategories.get(position), Snackbar.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(context, "Unable to Parse", Toast.LENGTH_LONG).show();
}
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray jsonArray = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jsonObject = null;
exCategories.clear();
//LOOP THROUGH THE ARRAY
for(int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
//RETRIEVE NAME
String exCatName = jsonObject.getString("exCatName");
//ADD IT TO ARRAY LIST
exCategories.add(exCatName);
}
//IF ITS SUCCESSFUL RETURN 1
return 1;
}
catch (JSONException e)
{
e.printStackTrace();
}
//IF IT IS NOT SUCCESSFUL RETURN 0
return 0;
}
}
Third Class
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
public class AddExpenseActivity extends SwipeFunctionActivity
{
private ImageView backImageView;
private TextView setDateTextView;
private EditText categoryEditText, amountEditText;
int year, month, day;
static final int DIALOG_ID = 0; //Initialise the variable to 0.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
setDateTextView = (TextView)findViewById(R.id.setDateTextView);
backImageView = (ImageView)findViewById(R.id.backImageView);
categoryEditText = (EditText)findViewById(R.id.categoryEditText);
amountEditText = (EditText)findViewById(R.id.amountEditText);
setDateTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showDialog(DIALOG_ID);
}
});
categoryEditText.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
pickCategoryMethod();
}
});
backImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
backMethod();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_ID)
{
return new DatePickerDialog(this, dpickerListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
AddExpenseActivity.this.year = year;
month = monthOfYear + 1;
day = dayOfMonth;
showDate(AddExpenseActivity.this.year, month, day);
//Toast.makeText(AddExpenseActivity.this, "Selected date: " + dayOfMonth + " / " + (monthOfYear+1) + " / " + year, Toast.LENGTH_LONG).show();
}
};
private void showDate(int year, int month, int day)
{
setDateTextView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
public void pickCategoryMethod()
{
String url = "http://192.168.0.3/myapp/fexcateg.php";
//
final Dialog dialog = new Dialog(AddExpenseActivity.this);
dialog.setContentView(R.layout.activity_pick_category);
dialog.setTitle(" Pick your Category");
final ListView pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
final ExDownloaderActivity downloader = new ExDownloaderActivity(this, url, pickCategoryListView);
//Execute download
downloader.execute();
//pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
//This makes the dialog visible.
dialog.show();
}
public void backMethod()
{
//startActivity(new Intent(getApplicationContext(), BalanceActivity.class));
finish();
}
#Override
public void onSwipeLeft()
{
super.onSwipeLeft();
startActivity(new Intent(getApplicationContext(), AddIncomeActivity.class));
finish();
}
#Override
public void onSwipeRight()
{
super.onSwipeRight();
startActivity(new Intent(getApplicationContext(), AddSavingActivity.class));
finish();
}
}
So for my problem now. I want when i click a category inside the dialog box, the categoryEditText variable i have in the trird class to change in the name of the item i clicked in the listview. First of all where do i have to write this code and secondly how to do it. I am kind of lost becasue is really a big app:/
Many thanks !!!

OnItemSelectedListener kept changing to adapter view

I want to create a spinner that retrieve data from database but OnItemSelectedListener won't work. It keeps suggesting to adapterview.OnclickListener but the coding need OnClickListenerOnly.
package com.example.win7.fyp;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class student_register extends Activity implements OnItemSelectedListener {
Toolbar toolbar;
private ProgressDialog progressDialog;
JsonParser jParser = new JsonParser();
private static String URL_TO_PASS = "http://arcafyp.xyz/chat/register_student.php";
SharedPreferences pref;
EditText username5, password5 ,advisorName5;
TextView advReg;
String username1;
String AndroidId;
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
private Spinner spinnerFood;
// Url to get all categories
private String URL_CATEGORIES = "http://ekinidris.site40.net/chat/advisorName.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_register);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);// 0 - for private mode
username5 = (EditText)findViewById(R.id.register_matrixno);
password5 = (EditText) findViewById(R.id.register_ic);
advisorName5 = (EditText) findViewById(R.id.advName);
spinnerFood.setOnItemSelectedListener(this);
spinnerFood = (Spinner) findViewById(R.id.spinFood);
categoriesList = new ArrayList<Category>();
// Add new category click event
new GetCategories().execute();
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(student_register.this);
pDialog.setMessage("Fetching advisor name..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("phone_id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
//populateSpinner();
}
}
/**
* Adding spinner data
* */
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
advisorName5.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerFood.setAdapter(spinnerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_student_register, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.register_send) {
new registerUser().execute();
String newCategory = advisorName5.getText().toString();
return true;
}
return super.onOptionsItemSelected(item);
}
class registerUser extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Intent i = getIntent();
String studentPhone_id = i.getStringExtra("phone_id").toString();
String studentUsername = username5.getText().toString();
progressDialog = new ProgressDialog(student_register.this);
progressDialog.setMessage("Processing Data" + studentPhone_id + studentUsername);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String studentUsername = username5.getText().toString(); // matrix no
String studentPassword = password5.getText().toString(); //cgpa
String studentAdvName = advisorName5.getText().toString(); //advisor name
Intent i = getIntent();
String studentPhone_id = i.getStringExtra("phone_id").toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("username",studentUsername));
param.add(new BasicNameValuePair("phone_id",studentPhone_id));
param.add(new BasicNameValuePair("password", studentPassword));
param.add(new BasicNameValuePair("advisorName", studentAdvName));
JSONObject json = jParser.makeHttpRequest("http://ekinidris.site40.net/chat/register_student.php","POST",param);
SharedPreferences.Editor editor = pref.edit();
Log.d("data", json.toString());
try {
int result = json.getInt("success");
if(result == 1) {
editor.putString("phone_id",studentPhone_id);
editor.commit();
Intent intent = new Intent(student_register.this, MainActivity.class);
intent.putExtra("phone_id", studentPhone_id);
intent.putExtra("username",studentUsername);
intent.putExtra("advisorName",studentAdvName);
startActivity(intent);
finish();
progressDialog.dismiss();
}else{
To be edited.....
put some action refreshing the page
}
}catch (JSONException e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
finish();
}
}
}
logcat
11-06 16:43:02.289 22071-22071/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.win7.fyp/com.example.win7.fyp.student_register}: java.lang.ClassCastException: com.example.win7.fyp.student_register cannot be cast to android.view.View$OnClickListener
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1968)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1993)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1159)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4507)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: com.example.win7.fyp.student_register cannot be cast to android.view.View$OnClickListener
at com.example.win7.fyp.student_register.onCreate(student_register.java:78)
at android.app.Activity.performCreate(Activity.java:4465)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1052)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1932)
            
follow this code-
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String msupplier=supplier.getSelectedItem().toString();
Log.e("Selected item : ",msupplier);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I used same answered by sud but with little modification which worked
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
// String msupplier=supplier.getSelectedItem().toString(); instead used below
Log.e("Selected item : ", (String) parent.getItemAtPosition(pos));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});

how to get all editext's value from ListItems in android and pass them to api

I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}

Categories

Resources