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

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);
}

Related

Adding onClick to RecyclerView Android [duplicate]

This question already has answers here:
RecyclerView Single Item ID
(2 answers)
Closed 5 years ago.
I have put together some code as shown below which gets data from a JSON file hosted on a server and puts it into a RecyclcerView. This has been working fine but any way I try to add a click method it does not work. I am looking to make it so that if I click one of the rows it will tell me the country it is. I have no idea where I am going wrong but I will attach my code below which gets the JSON data and puts it into the RecyclerView.
Thanks
package com.example.curtisboylan.myapplication;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Objects;
public class MainRecycler extends AppCompatActivity {
private ArrayList countries;
private static String url = "http://curtisboylan.me/mygeek/mygeektest.php";
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
countries = new ArrayList<>();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_recycler);
initViews();
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
TextView txtView = (TextView) findViewById(R.id.textView5);
if (Objects.equals(message, "di1")){
txtView.setText("Diagnostics");
}
else if (Objects.equals(message, "screen1")){
txtView.setText("Screen Repair");
}
setTitle("Available Technicians");
}
private void initViews(){
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainRecycler.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 jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("MyGeek");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
//String email = c.getString("email");
//String address = c.getString("address");
//String gender = c.getString("gender");
// Phone node is JSON Object
// JSONObject phone = c.getJSONObject("phone");
// String mobile = phone.getString("mobile");
// String home = phone.getString("home");
// String office = phone.getString("office");
countries.add(c.getString("name"));
}
} 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);
pDialog.hide();
RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);
RecyclerView.Adapter adapter = new DataAdapter(countries);
recyclerView.setAdapter(adapter);
}
}
}
Instead of adding a click listener on the Recycler view, try adding click listener in the adapter class, in the onBindViewHolder method. That is how you will get the exact item on which the click was executed.
#Override
public void onBindViewHolder(Viewholder holder, final int position) {
YourClassObject item = YourClassObjectList.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(view.getContext(), "Recycle Click" + position, Toast.LENGTH_SHORT).show();
}
});
Create a interface in your Adapter class
public interface EventsCatalogsAdapter{
void onClickImageCategory(Catalogs catalog);
}
Create a atribute of EventsCatalogsAdapter
private EventsCatalogsAdapter event;
Create constructor
public CatalogsAdapter(EventsCatalogsAdapter event) {
this.event = event;
}
Add setOnClickListener in onBindViewHolder
public void onBindViewHolder(final CatalogsViewHolder holder, final int position){
holder.imageCatalog.setOnClickListener(holder);
}
In you RecyclerView.ViewHolder implements onClickListener event.
class CatalogsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private ImageView imageCatalog;
private TextView tvCatalogName;
private View vLegendCatalog;
public CatalogsViewHolder(View itemView) {
super(itemView);
imageCatalog = (ImageView) itemView.findViewById(R.id.i =vCatalogItem);
tvCatalogName = (TextView)itemView.findViewById(R.id.tvCatalogName);
vLegendCatalog = itemView.findViewById(R.id.vLegendCatalog);
}
#Override
public void onClick(View v) {
event.onClickImageCategory(catalogsList.get(getAdapterPosition()));
}
}

Data didnt load, and not error or warning display

i got trouble, im try convert my fragment into activity, and when im try running the apps, all data not load and no warning or error shown, pls someone help
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
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();
// Movies json url
private static final String url = "http://......";
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);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
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 {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("tipe").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
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);
return rootView;
}
#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
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// 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());
dialog.show();
}
}
if default in Fragment its running perfectly and no problem, but when im try using activity all data not load.
I can't see any code that would run when the activity is created. You have an onCreateView method (which I am guessing you are carrying over from your Fragment based implementation). Unless somewhere in your code (which I cannot see how) you are calling that method, it never gets called since it is not part of the Activity lifecycle. I would copy over the entire code from that method to onCreate method (as a starting point) and delete the method. I would then make the following changes to the first few lines
// View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Noticed that I commented out the above line and changed the line below
final ListView listView = (ListView) findViewById(R.id.list);
I am not suggesting that this will solve all of your problems as there might be (likely) other issues, but you should potentially be the first step. I strongly suggest you get more familiar with the Activity and Fragment classes and become more comfortable with their lifecycles. Also, you should get rid of
public RekomendasiExercise() {
// Required empty public constructor
}
Best of luck

Convert Fragment Code to Activity Code

I am trying to convert my Fragment Code to Activity code, but when I try to run the Activity, the Activity opens but the data is null. Here my code
Fragment
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
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 ArmBicepFragment extends Fragment implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = ArmBicepFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:.......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public ArmBicepFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
adapter = new CustomListAdapter(getActivity(), exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
// 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 {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("name").equals("bicep")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
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);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// 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();
}
}
And here my convert result from Fragment (Nothing Error or warning)
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
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;
/**
* Created by Felix on 5/15/2016.
*/
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:............";
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);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
final ListView listView = (ListView) rootView.findViewById(R.id.list);
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 {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
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);
return rootView;
}
#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
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// 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();
}
}
onCreateView
is not a part of activity's lifecycle. You need to move stuff from this method to onCreate:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
final ListView listView = (ListView) findViewById(R.id.list);
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 {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
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);
}
You should put your codes in onCreate . Copy/paste the below codes.
public class RekomendasiExercise extends AppCompatActivity implements AdapterView.OnItemClickListener{
// Log tag
private static final String TAG = AbdominalFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:............";
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);
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 {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("nama").equals("abdominal")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
// adding movie to movies array
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;
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
}
#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
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// 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();
}
}
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
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 com.elite.youvaa.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class ArmBicepFragment extends Activity implements AdapterView.OnItemClickListener {
// Log tag
private static final String TAG = ArmBicepFragment.class.getSimpleName();
// Movies json url
private static final String url = "http:.......";
private ProgressDialog pDialog;
private List<Exercise> exerciseList = new ArrayList<Exercise>();
private ListView listView;
private CustomListAdapter adapter;
public ArmBicepFragment() {
// 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);
adapter = new CustomListAdapter(getApplicationContext(), exerciseList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getApplicationContext());
// 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 {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("name").equals("bicep")) {
exercise.setNama(obj.getString("nama"));
exercise.setGambar1(obj.getString("gambar1"));
// Genre is json array
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 View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_list, container, false);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
// Create custom dialog object
final Dialog dialog = new Dialog(getContext());
// Include dialog.xml file
dialog.setContentView(R.layout.dialog); // layout of your dialog
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbnail1 = (NetworkImageView ) dialog.findViewById(R.id.gambar1);
thumbnail1.setImageUrl(exerciseList.get(position).getGambar1(), imageLoader);
// 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();
}
}

Two activities sending data to each other

Two activities are sending data to each other.
The first activity has a custom list view. The second has one text view and three buttons to increase and decrease a value.
When I click on the first activity, the second activity opens. The second activity increases the text view value and clicked the button. Data goes to the first activity. Same process again.
My problem is that the total value is not displayed in the first activity.
How can i show all increase and decrease values from the second activity in the first activity?
First activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
public class DetaisRESTActivity extends Activity {
String messagevaluename,valueid,valueid1,valuename,pos;
public String countString=null;
String nameofsubmenu;
public int count=0;
public String message=null;
public String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public SharedPreferences.Editor edit;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detais_rest);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
SharedPreferences preferences=getSharedPreferences("temp1", 1);
// SharedPreferences.Editor editor = preferences.edit();
int na=preferences.getInt("COUNTSTRING1",0);
Log.i("asasassas",""+na);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
// SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
// Reading all contacts
/*
Log.d("Reading: ", "Reading all contacts..");
List<Contact> contacts = db.getAllContacts();
for (Contact cn : contacts) {
String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
cn.getPhoneNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
*/
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Log.i("postititi",""+position);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
nameofsubmenu=data.getStringExtra("name");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
Log.i("submenu",nameofsubmenu);
//ruppees.setText(message);
//editor.putInt("count",na);
//editor.commit();
//Log.i("asasassasasdsasdasd",""+na);
// mTitleTextView.setText(Arrays.toString(message1));
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("count",message1);
i.putExtra("submenu",nameofsubmenu);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#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_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
public void OnPause(){
super.onPause();
}
}
Second activity's code:
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String[] cccc;
ImageButton positive,negative;
String position;
static int count = 1;
int tot_amt = 0;
public String countString=null;
String name,price;
String valueid,valueid1,valuename;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
SharedPreferences preferences;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
preferences = getSharedPreferences("temp1",1);
editor = preferences.edit();
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
editor.putInt("COUNTSTRING1", count);
editor.commit();
editor.clear();
Log.i("sunder sharma",""+count);
countString= String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
if (count > 1)
count--;
editor.putInt("COUNTSTRING1", count);
editor.commit();
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/* Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
SqliteController db = new SqliteController(QuentityActivity.this);
db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));
*/
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
intent.putExtra("name",name);
setResult(2,intent);
finish();//finishing activity
}
});
}
#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_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Collect the data from second activity and put into below intent .Then you will receive first activity.
Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString); //add data
startActivity(myIntent);

CalledFromWrongThreadException when trying to disable button

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.

Categories

Resources