CalledFromWrongThreadException when trying to disable button - android

I'm getting this error:
10-06 09:09:25.466:
E/not work(1300):
pass exceptionandroid.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
my Android project pass above error when i am try to disabled button.
if (success == 1) {
Log.i("enable", "working//////");
upload.setEnabled(true);
sendDeseaseDetails.setEnabled(false);
}else{
upload.setActivated(false);
sendDeseaseDetails.setEnabled(true);
}
above code run time pass this error. what is wrong........? please help me...........!
This is full code:
package viewActivity;
//import java.io.Externalizable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.src.adms.R;
import controller.DBConnection;
//import android.R.string;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.text.Editable;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("SimpleDateFormat")
public class Send_deases_Detail extends Activity {
Spinner diseaseSpinner; // disease type
Spinner weatherSpinner; // get weather
Spinner districSpinner; // get district
Spinner soilConditionSpinner; // get soil condition
ImageButton upload; // upload images
Button clear; // clear field
Button sendDeseaseDetails; // button send disease details
int success = 0; // use, to know disease details send successfully
private Bundle extraslogin; // to get username and password
private String userName;
#SuppressWarnings("unused")
private String password;
private String userType;
private int deases_id;
private String diseaseType;
private String weather;
private String soilCondition;
private String district;
private EditText plantName;
private EditText region;
private EditText userDescription;
private static final String SEND_DESEASE_URL = "http://10.0.2.2:80/ADMS/andrioidConnection/send_deases_detail.php";
// private static final String SEND_DESEASE_URL
// ="http://admstest.netau.net/ADMS/andrioidConnection/send_deases_detail.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USER_TYPE = "usertype";
private static final String TAG_DEASES_ID = "deases_id";
DBConnection dbConnection = new DBConnection();
private ProgressDialog dialogBox;
// private Object EditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.deases_detail);
// get user name and password form LoIin
extraslogin = getIntent().getExtras();
userName = extraslogin.getString("user_name");
password = extraslogin.getString("pass_word");
plantName = (EditText) findViewById(R.id.editPlantName);
diseaseSpinner = (Spinner) findViewById(R.id.diseaseTypeSpinner);
weatherSpinner = (Spinner) findViewById(R.id.weather_Spinner);
districSpinner = (Spinner) findViewById(R.id.district_Spinner);
soilConditionSpinner = (Spinner) findViewById(R.id.soil_condition_Spinner);
// get id of image upload button
upload = (ImageButton) findViewById(R.id.imagebtUpload);
//upload.setEnabled(false); // default set false
// get date
// ...................................................................................
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
"d/M/yy h:m:s a");
String stringDate = simpleDateFormat.format(calendar.getTime());
TextView textView = (TextView) findViewById(R.id.txtDate);
textView.setText(stringDate);
// this for disease type spinner
ArrayAdapter<CharSequence> diseasearrArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.diseaseType_array,
android.R.layout.simple_list_item_1);
diseasearrArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
diseaseSpinner.setAdapter(diseasearrArrayAdapter);
diseaseSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// get selected item
diseaseType = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// this for weather type spinner
ArrayAdapter<CharSequence> weatherArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.weather_array,
android.R.layout.simple_list_item_1);
weatherArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weatherSpinner.setAdapter(weatherArrayAdapter);
weatherSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// to get selected item
weather = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// this for district spinner
ArrayAdapter<CharSequence> districArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.district_array,
android.R.layout.simple_list_item_1);
districArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
districSpinner.setAdapter(districArrayAdapter);
districSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// get selected item
district = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// this for soil
// condition..........................................................................................................
ArrayAdapter<CharSequence> soilArrayAdapter = ArrayAdapter
.createFromResource(this, R.array.soil_array,
android.R.layout.simple_list_item_1);
soilArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
soilConditionSpinner.setAdapter(soilArrayAdapter);
soilConditionSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
((TextView) parent.getChildAt(0)).setTextSize(15);
// to get selected item
soilCondition = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
// ..............................................................................
region = (EditText) findViewById(R.id.editRegion);
userDescription = (EditText) findViewById(R.id.editDescription);
// give action to send disease details
// button........................................................
sendDeseaseDetails = (Button) findViewById(R.id.btSendDetails);
sendDeseaseDetails.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new sendDetail().execute();
}
});
// ..............................................................................
// give action to cancel
// button...................................................................
clear = (Button) findViewById(R.id.btCancel);
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clear();
//Toast.makeText(getApplicationContext(), "clear field",Toast.LENGTH_SHORT).show();
}
private void clear() {
plantName.setText("");
region.setText("");
userDescription.setText("");
upload.setEnabled(false);
sendDeseaseDetails.setEnabled(true);
weatherSpinner.setSelection(0);
soilConditionSpinner.setSelection(0);
districSpinner.setSelection(0);
diseaseSpinner.setSelection(0);
configureImageUploadButton();
}
});
clear.performClick();
}
// configure Image Upload Button......................................
private void configureImageUploadButton() {
// upload.setEnabled(true);
upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click image button",
Toast.LENGTH_SHORT).show();
// pass data to image Take activity
Intent imageTakeActivity = new Intent(Send_deases_Detail.this,
ImageTakeActivity.class);
imageTakeActivity.putExtra("user_type", userType);
imageTakeActivity.putExtra("deases_id", deases_id);
success=0;
//enable();
// go to ImageTakeActivity
startActivity(imageTakeActivity);
finish();
}
});
}
// .................................................................................
protected void enable() {
if (success == 1) {
Log.i("enable", "working//////");
upload.setEnabled(true);
sendDeseaseDetails.setEnabled(false);
}else{
upload.setEnabled(false);
sendDeseaseDetails.setEnabled(true);
}
}
class sendDetail extends AsyncTask<String, String, String> {
// preprocessing part
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialogBox = new ProgressDialog(Send_deases_Detail.this);
dialogBox.setTitle("Processing...");
dialogBox.setMessage("Please wait...");
dialogBox.setIndeterminate(false);
dialogBox.setCancelable(true);
dialogBox.show();
}
// back ground run process
#Override
protected String doInBackground(String... args) {
String plant_name = plantName.getText().toString();
String region_name = region.getText().toString();
String user_discription = userDescription.getText().toString();
try {
// add first name, last name, Email & password to array list
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_name", userName));
// params.add(new BasicNameValuePair("pass_word", password));
params.add(new BasicNameValuePair("disease_type", diseaseType));
params.add(new BasicNameValuePair("weather", weather));
params.add(new BasicNameValuePair("soil_condition",
soilCondition));
params.add(new BasicNameValuePair("district", district));
params.add(new BasicNameValuePair("plant_name", plant_name));
params.add(new BasicNameValuePair("region _name", region_name));
params.add(new BasicNameValuePair("user_discription",
user_discription));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = dbConnection.createHttpRequest(
SEND_DESEASE_URL, "POST", params);
// check your register for json response
Log.d("Send detail attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
deases_id = json.getInt(TAG_DEASES_ID);
userType = json.getString(TAG_USER_TYPE);
Log.d("deases_id", String.valueOf(deases_id));
if (success == 1) {
Log.d("Send Desease Detaiail Successful!", json.toString());
//configureImageUploadButton();//comment
Log.i("after!", "???pass configureImageUploadButton");
// configureImageUploadButton();
// finish();
// startActivity(i);
try {
enable(); // call to image button enable method
//finish();
} catch (Exception exception) {
Log.e("not work", "pass exception"+exception);
}
Log.i("work", "in back ground process......");
return json.getString(TAG_MESSAGE);
} else {
Log.d("Send detail fail!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialogBox.dismiss();
if (result != null) {
Toast.makeText(Send_deases_Detail.this, result,
Toast.LENGTH_LONG).show();
}
}
}
}
please help me

In android you need to perform any actions on views from the main UI thread. This post Running code in main thread from another thread will give you an idea of how to do so.

Related

how to work on BUY NOW button in android?

I am developing an Android eCommerce application in which there are two different buttons. The first one is an ADD TO CART button and the other one is a BUY NOW button.
When I click on the ADD TO CART button, it successfully places the item in the cart and after I click on the cart button, the app proceeds to the Cart Activity. I did the same for BUY NOW but the issue is how do I update my cart and move to Cart Activity on a single click?
ProductDescription.java:
package com.www.prashant;
import android.app.ProgressDialog;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.daimajia.slider.library.SliderLayout;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class ProductDescription extends Fragment {
View V;
int position;
ImageView product_image;
TextView product_desc;
public TextView price;
public TextView specialPrice;
TextView product_name;
ImageLoader image;
SliderLayout product_images;
Button sharbtn;
public TextView txt_qty;
public Button btn_plus;
public Button btn_buy;
ProgressDialog pdialog;
public int sum=0;
public int remove=0;
String cartMessage;
String cartMessage1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
Constants.lastDetails = true;
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.product_details, container, false);
//Set Navigation mode as Statndard
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
V=v;
//get Product Position
position = Constants.product_position;
//Initialize ids
product_image=(ImageView) V.findViewById(R.id.product_image);
product_desc=(TextView) V.findViewById(R.id.textProductDescription);
price=(TextView) V.findViewById(R.id.text1);
specialPrice = (TextView) V.findViewById(R.id.textSpecialPrice);
product_name=(TextView) V.findViewById(R.id.textProductName);
//sharbtn=(Button)V.findViewById(R.id.sharbtn);
image=new ImageLoader(getActivity());
image.DisplayImage(Constants.Product_image.get(position), product_image);
product_name.setText(Constants.Product_name.get(position));
product_desc.setText(Constants.Product_desc.get(position));
// product_adesc.setText(Constants.Product_adesc.get(position));
if(Constants.Product_specialPrice.get(position) < Constants.Product_price.get(position)
&& Constants.Product_specialPrice.get(position)!=0){
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
specialPrice.setText(String.format("%.2f",Constants.Product_specialPrice.get(position)));
}
else {
price.setText(String.format("%.2f",Constants.Product_price.get(position)));
specialPrice.setText(null);
}
btn_plus = (Button) V.findViewById(R.id.btn_plus);
btn_buy = (Button) V.findViewById(R.id.btn_buy);
// btn_minus = (ImageButton) V.findViewById(R.id.btn_minus);
txt_qty = (TextView) V.findViewById(R.id.txt_qty);
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
**/* Button Click Listener for Add Qty*/**
btn_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
**/* Button Click Listener for Buy Qty*/**
btn_buy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Constants.Product_pos=position;
remove=0;
sum = Integer.parseInt(txt_qty.getText().toString())+1;
Constants.Product_qty.set(position, sum);
cartMessage1="Adding product to cart...";
cartMessage="Product was added successfully";
new updateCart().execute();
}
});
product_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ImageFragment imageFrag=new ImageFragment();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,imageFrag,null).addToBackStack(null).commit();
getActivity().setTitle("Images");
}
});
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
//((MainActivity)getActivity()).resetActionBar(true, DrawerLayout.LOCK_MODE_LOCKED_OPEN);
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
MainActivity.getInstance().CallFragment(Constants.position);
}
return true;
}
//Add product to cart task
public class updateCart extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage, Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count += 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
//Remove product from cart
public class removeCartProduct extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage(cartMessage1);
pdialog.setCanceledOnTouchOutside(false);
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
parseJSONDataAddProductToCart();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pdialog.isShowing()){
pdialog.dismiss();
pdialog=null;
}
Toast.makeText(getActivity(), cartMessage,Toast.LENGTH_LONG).show();
//Update Notification Count in action bar icon
//Constants.cart_count -= 1;
//txt_qty.setText(String.valueOf(sum));
MainActivity.getInstance().updateHotCount(Constants.ProductCart_Id.size());
txt_qty.setText(String.valueOf(Constants.Product_qty.get(position)));
// if internet connection and data available show data on list
// otherwise, show alert text
}
}
public void parseJSONDataAddProductToCart(){
try {
SoapObject item = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntity");
SoapObject request;
int qty;
if(remove==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductAdd");
qty=1;
}else{
qty= Constants.Product_qty.get(Constants.Product_pos);
if(qty==0){
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductRemove");
}else{
request = new SoapObject(Constants.NAMESPACE, "shoppingCartProductUpdate");
}
}
// add paramaters and values
request.addProperty("sessionId", Constants.sessionId);
PropertyInfo pinfo = new PropertyInfo();
pinfo.setName("product_id");
pinfo.setValue(Constants.Product_ID.get(Constants.Product_pos));
pinfo.setType(String.class);
item.addProperty(pinfo);
pinfo = new PropertyInfo();
pinfo.setName("qty");
pinfo.setValue(qty);
pinfo.setType(Double.class);
item.addProperty(pinfo);
SoapObject EntityArray = new SoapObject(Constants.NAMESPACE, "shoppingCartProductEntityArray");
EntityArray.addProperty("products", item);
request.addProperty("quoteId", Constants.cartId);
request.addProperty("products",EntityArray);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
//Web method call
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.URL);
androidHttpTransport.debug = true;
androidHttpTransport.call("", envelope);
//get the response
Object result = envelope.getResponse();
Constants.CartaddStatus=result.toString();
if(Constants.CartaddStatus == "true"){
if (Constants.ProductCart_Id.isEmpty()){
Constants.cartArrayPos=0;
}
if (!Constants.ProductCart_Id.contains(Constants.Product_ID.get(Constants.Product_pos))) {
Constants.ProductCart_Id.add(Constants.cartArrayPos,Constants.Product_ID.get(Constants.Product_pos));
Constants.ProductCart_Img.add(Constants.cartArrayPos,Constants.Product_image.get(Constants.Product_pos));
Constants.ProductCart_Price.add(Constants.cartArrayPos, Constants.Product_price.get(Constants.Product_pos));
Constants.cartArrayPos+=1;
}
if (qty==0){
Constants.ProductCart_Id.remove(Constants.Product_pos);
Constants.ProductCart_Img.remove(Constants.Product_pos);
Constants.ProductCart_Price.remove(Constants.Product_pos);
Constants.cartArrayPos-=1;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}
}
ActivityCart:
package com.www.prashant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;
/**
* Created by Prashant on 10/16/2016.
*/
public class ActivityCart extends Fragment {
int run;
ProgressDialog pdialog;
View v;
GridView list2;
CartImageLoadAdapter adapter;
public static ActivityCart sActivityCart;
public Double TotalPrice= 0.00;
TextView btn_place_order;
TextView btn_place;
Button btn_place_ord;
static String TotalProductCartPrice;
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.cart, container, false);
sActivityCart = this;
((MainActivity)getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
((MainActivity)getActivity()).getSupportActionBar().setNavigationMode(((MainActivity) getActivity()).getSupportActionBar().NAVIGATION_MODE_STANDARD);
list2=(GridView)v.findViewById(R.id.cartlist);
//list2.setBackgroundColor(Color.BLACK);
//list2.setVerticalSpacing(1);
// list2.setHorizontalSpacing(1);
clearData();
btn_place_order = (TextView) v.findViewById(R.id.btn_place_order);
// btn_place = (TextView) v.findViewById(R.id.btn_place);
btn_place_ord = (Button) v.findViewById(R.id.btn_place_ord);
btn_place_ord.setOnClickListener(listener);
return v;
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Constants.lastDetails = false;
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(null);
((MainActivity)getActivity()).actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
Constants.cartEntry=1;
new getDataTask().execute();
}
void clearData(){
Constants.Product_ID.clear();
Constants.Product_name.clear();
Constants.Product_price.clear();
Constants.Product_image.clear();
Constants.Product_qty.clear();
Constants.Product_specialPrice.clear();
Constants.Product_desc.clear();
//Constants.Product_adesc.clear();
}
#Override
public void onDestroy()
{
// Remove adapter refference from list
if (run==1) {
list2.setAdapter(null);
//Refresh cache directory downloaded images
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
super.onDestroy();
}
//Click Listner for place order button
public View.OnClickListener listener=new View.OnClickListener(){
#Override
public void onClick(View arg0) {
if(run == 1) {
// Call Login Function
if(Constants.Customer_FirstName.equals(""))
{
CartLogin CartLogin=new CartLogin();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CartLogin,null).addToBackStack(null).commit();
getActivity().setTitle("Login");
}
else {
// Call Shipping Information Function
ActivityCustomerAddress CustomerAddress=new ActivityCustomerAddress();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,CustomerAddress,null).addToBackStack(null).commit();
getActivity().setTitle("Shipping");
}
}
else
Toast.makeText(getActivity(),"Cart is Empty",Toast.LENGTH_LONG).show();
}
};
// Image urls used in LazyImageLoadAdapter.java file
public class getDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (pdialog==null){
pdialog=new ProgressDialog(getActivity());
pdialog.setMessage("Loading...");
pdialog.setCanceledOnTouchOutside(getRetainInstance());
pdialog.setCancelable(false);
pdialog.show();
}
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
// parse json data from server in background
if (!Constants.ProductCart_Id.isEmpty()){
parseJSONData();
run=1;
}else{
run=0;
}
//Get Product Prices
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
// Create custom adapter for listview
if (run==1) {
String[] images = new String[Constants.Product_image.size()];
images = Constants.Product_image.toArray(images);
adapter = new CartImageLoadAdapter(getActivity(), images);
//Set adapter to listview
list2.setAdapter(adapter);
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
}else{
if (pdialog.isShowing()) {
pdialog.dismiss();
pdialog = null;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Cart is Empty").setMessage("Start Shopping now !!").create().show();
run=0;
}
// if internet connection and data available show data on list
// otherwise, show alert text
// btn_place_order.setText(String.format("Total: %.2f Place Order", TotalPrice));
btn_place_order.setText(String.format("%.2f ", TotalPrice));
TotalProductCartPrice= btn_place_order.getText().toString();
}
}
// method to parse json data from server
public void parseJSONData(){
HttpClient Client = new DefaultHttpClient();
// Create URL string
String URL = "http://prashant.com/customApi/cartDetails.php?cartId="+Constants.cartId;
//Log.i("httpget", URL);
JSONParser parser =new JSONParser();
try
{
String SetServerString = "";
// Create Request to server and get response
HttpGet httpget = new HttpGet(URL);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
SetServerString = Client.execute(httpget, responseHandler);
Constants.Login=SetServerString;
JSONArray array=new JSONArray(SetServerString);
for (int i = 0; i < array.length(); i++) {
JSONObject obj=array.getJSONObject(i);
Constants.Product_ID.add(Long.parseLong(obj.getString("productId")));
Constants.Product_name.add(obj.getString("name"));
Double price= Double.valueOf(obj.getString("price"));
int Qty= Integer.parseInt(obj.getString("qty"));
Constants.Product_price.add(price*Qty);
Constants.Product_image.add(obj.getString("imageurl"));
Constants.Product_qty.add(Integer.valueOf(obj.getString("qty")));
Constants.Product_specialPrice.add((Double.valueOf(obj.getString("spprice")))*Qty);
// Total Sum of Cart Item price
TotalPrice += Double.valueOf(Double.valueOf(obj.getString("spprice"))*Qty);
}
// Show response on activity
}
catch(Exception ex)
{
}
}
public static ActivityCart getInstance() {
return sActivityCart;
}
public void SyncCart(){
// Call Shipping Information Function
ActivityCart SyncCart=new ActivityCart();
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.main_content,SyncCart,null).addToBackStack(null).commit();
getActivity().setTitle("Cart");
}
}

In Activity.class want to get Spinner Item Text from Fragment.class

im still confused about to get spinner item text.
So, In Activity.class i want to get Spinner Item Text from Fragment.class but idk how to get Spinner Item Text from fragment,
anyone can help?
Fragment.class
final Spinner spinner = (Spinner) rootView.findViewById(R.id.choices);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
// TODO Auto-generated method stub
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
if (SpinerValue3.equals("Item 1")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();=
} else if (SpinerValue3.equals("Item 2")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 3")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 4")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 5")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}else if (SpinerValue3.equals("Item 6")) {
Toast.makeText(getActivity().getBaseContext(),
"Try Choose : " + SpinerValue3,
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
if above im explain for make a toast, but how to get text spinner item on Activity.class
Activity.class Iwant to change SPINNERITEM (On code below) with get Spinner item text from Fragment
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.NetworkImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
private static final String url = "http://........php";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public RekomendasiExercise() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView)findViewById(R.id.list);
final Spinner spinner = (Spinner) findViewById(R.id.choices);
adapter = new CustomListAdapter(this, exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
if(exerciseList.isEmpty()) {
// Creating volley request obj
JsonArrayRequest exerciseReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
exerciseList.clear();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
String text = spinner.getSelectedItem().toString();
int positionitem = spinner.getSelectedItemPosition();
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("type").equals("SPINNERITEM")) {
exercise.setNama(obj.getString("name"));
exercise.setTipe(obj.getString("type"));
exercise.setMainmuscle(obj.getString("mainmuscle"));
exerciseList.add(exercise);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(exerciseReq);
}else{
hidePDialog();
}
listView.setOnItemClickListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(this);
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
// Set dialog title
dialog.setTitle("Detail");
// set values for custom dialog components - text, image and button
TextView nama = (TextView) dialog.findViewById(R.id.nama);
nama.setText("Nama = " + exerciseList.get(position).getNama());
// similar add statements for other details
dialog.show();
}
}
My recommendation would be to follow the standard communication model for Activity and Fragment where the Activity implements a callback interface defined in the Fragment.
Check this link for details.
In your onItemSelected method of the spinner, you can call the callback method of the Activity with the selected spinner value.
This is how you could do in OOPS ways
Step 1) Make a spinner Item Value variable in Activity Class
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
private String currentSpinnerItem ;
/*
set current spinner item value
*/
public void setCurrentSpinnerItem(String itemValue)
{
this.currentSpinnerItem = itemValue ;
//Do stuffs in activity with new value
}
Step 2) Now in your fragment class update currentItemSpinner value like this
#Override
public void onItemSelected(AdapterView<?> parent, View v,
int postion, long arg3) {
String SpinerValue3 = parent.getItemAtPosition(postion).toString();
//Update spinner selected item value in activity
((RekomendasiExercise) getActivity).setCurrentSpinnerItem(SpinerValue3);
}

Using android radio button to execute method

I have 2 radiobuttons and 1 button. I want that when i click the normal button it checks which radio button is checked and executes a method based on that. The following is the code i have used but the app crashes when i click the button
#Override
public void onClick(View v) {
radioGroup = (RadioGroup) v.findViewById(R.id.radioPost);
rdpublic=(RadioButton) v.findViewById(R.id.radioPublic);
rdprivate=(RadioButton) v.findViewById(R.id.radioPrivate);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(rdpublic.isChecked())
{
new PostPublic().execute();
}
else if(rdprivate.isChecked())
{
new PostPrivate().execute;
}
}
});
}
Try this.....
normalBtn= (Button) findViewById(R.id.Btn);
rdpublic=(RadioButton) findViewById(R.id.radioPublic);
rdprivate=(RadioButton) findViewById(R.id.radioPrivate);
normalBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
if(rdpublic.isChecked())
{
new PostPublic().execute();
}
else if(rdprivate.isChecked())
{
new PostPrivate().execute;
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
Why are you using the button view to find the RadioButtons and Group? Instead of v.findViewById, you should just use findViewById.
your code assumes that your Buttons or RadioButtons are child Views of the passed View v. Which is actually wrong and that is why you are getting an NPE.
This is the full code.
package com.project.bsc.radianstores;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class PostEnquiry extends Fragment implements OnClickListener {
public String[] sItemType;
public int position =0;
private EditText Message;
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String POST_PRIVATE_URL = "http://192.168.1.102/webservice/privateenquiry.php";
private static final String POST_PUBLIC_URL = "http://192.168.1.102/webservice/publicenquiry.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private Button BtnSave;
private RadioGroup radioGroup;
private RadioButton rdpublic;
private RadioButton rdprivate;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.enquiry, container, false);
BtnSave = (Button) v.findViewById(R.id.sendEnquiry);
Message = (EditText)v.findViewById(R.id.MessageBox);
Spinner spItemType = (Spinner) v.findViewById(R.id.spinnerItemType);
sItemType = getResources().getStringArray(R.array.ItemType);
BtnSave.setOnClickListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, sItemType);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spItemType.setAdapter(dataAdapter);
//setting up listener for the spinner
spItemType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
position = index;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
return v;
}
#Override
public void onClick(View v) {
radioGroup = (RadioGroup) v.findViewById(R.id.radioPost);
rdpublic=(RadioButton) v.findViewById(R.id.radioPublic);
rdprivate=(RadioButton) v.findViewById(R.id.radioPrivate);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(checkedId == rdpublic.getId()) {
new PostPublic().execute();
}
else if (checkedId == rdprivate.getId()) {
//new PostPrivate().execute();
}
}
});
}
class PostPublic extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Posting Enquiry...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String strItemType = sItemType[position];;
String strMessage = Message.getText().toString();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
String strUsername = sp.getString("Username", "");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", strUsername));
params.add(new BasicNameValuePair("Item_Type", strItemType));
params.add(new BasicNameValuePair("Message", strMessage));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_PUBLIC_URL, "POST", params);
// full json response
Log.d("Enquiry Posting attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Enquiry Posted Successful!", json.toString());
return json.getString(TAG_MESSAGE);
}else{
Log.d("Posting Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null)
Toast.makeText(getActivity(), file_url, Toast.LENGTH_LONG).show();
}
}
}

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 do i get this in asynctask

i got my app working so it returns the information from a json api.
now i realize that i have to put everything in a asynch task so it doesn't crash as much
and a progress dialog is easier, only i really don't know how to do this so im wondering if somebody knows a really good tutorial or wants to edit my code a bit to get my started
package net.thinkbin;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class culture extends ListActivity {
private static final String TITLE = "Title";
private static final String AUTHOR = "Author";
private static final String VIEWS = "Views";
private static final String RATES = "Rates";
private static final String CONTENT = "Content";
final Context context = this;
JSONArray ideas = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder2);
Button view = (Button) findViewById(R.id.button1);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.TUTORIAL1"));
overridePendingTransition(0, 0);
finish();
}
});
Button share = (Button) findViewById(R.id.button2);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.SHARE"));
overridePendingTransition(0, 0);
finish();
}
});
Button menu = (Button) findViewById(R.id.buttonhome);
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Loading...");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.hourglass);
dialog.show();
Thread th = new Thread(new Runnable() {
public void run() {
startActivity(new Intent("net.thinkbin.MENU"));
overridePendingTransition(0, 0);
dialog.dismiss();
finish();
}
});
th.start();
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.spinnerorder,
android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.cultureorder);
s.setAdapter(adapter2);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter2, View view,
int position, long id) {
if (position == 1) {
startActivity(new Intent("net.thinkbin.CULTURE2"));
overridePendingTransition(0, 0);
finish();
}
if (position == 2) {
startActivity(new Intent("net.thinkbin.CULTURE3"));
overridePendingTransition(0, 0);
finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://www.thinkbin.net/include/api/index.php? cat=Culture&type=Newest&i=10");
try {
ideas = json.getJSONArray("Ideas");
for (int i = 0; i < ideas.length(); i++) {
JSONObject c = ideas.getJSONObject(i);
String title = c.getString(TITLE);
String author = c.getString(AUTHOR);
String views = c.getString(VIEWS);
String rates = c.getString(RATES);
String content = c.getString(CONTENT);
HashMap<String, String> map = new HashMap<String, String> ();
map.put(TITLE, "Title: " + title);
map.put(AUTHOR, "Author: " + author);
map.put(VIEWS, "Views: " + views);
map.put(RATES, "Rates: " + rates);
map.put(CONTENT, content);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main2,
new String[] { TITLE, AUTHOR, VIEWS, RATES, CONTENT },
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item3,
R.id.item4, R.id.item5 });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Title2 = ((TextView) view.findViewById(R.id.item_title))
.getText().toString();
String Author2 = ((TextView) view
.findViewById(R.id.item_subtitle)).getText().toString();
String Content2 = ((TextView) view.findViewById(R.id.item5))
.getText().toString();
Intent in = new Intent(getApplicationContext(), idea.class);
overridePendingTransition(0, 0);
in.putExtra(TITLE, Title2);
in.putExtra(AUTHOR, Author2);
in.putExtra(CONTENT, Content2);
startActivity(in);
}
});
}
}
There is good class AsyncTask to do something Asyncronius in Android.
Example:
private class DownloadFilesTask extends AsyncTask
{
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
} }
http://developer.android.com/reference/android/os/AsyncTask.html

Categories

Resources