I have a code here and i want to pass the hash map function by clicking save button. I looked Here but cannot find the solution for me.
oN Click the button i need to pass the hasmap.Anyone please help for this.My Codes is:
btnsave = (Button) findViewById(R.id.btn_save);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
expandableDataPump.getData();
Intent intent = new Intent(getApplicationContext(), ExpandableList.class);
//HERE I NEED TO PASS HASHMAP
intent.putStringArrayListExtra("details",(HashMap<String,>) expandableDataPump.getData());
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(MainActivity.this, "You have an ERROR", Toast.LENGTH_LONG).show();
}
}
});
}
public class ExpandableDataPump {
public HashMap<String, List<String>> getData() {
HashMap<String, List<String>> expandableListDetail = new HashMap<>();
for (int i = 2; i < container.getChildCount(); i++) {
if (container.getChildAt(i) instanceof RelativeLayout) {
List<String> childs = new ArrayList<>();
childs.add(((TextView)container.getChildAt(i).findViewById(R.id.textout)).getText().toString());
expandableListDetail.put(txtHeading.getText().toString(), childs);
}
}
return expandableListDetail;
}
}
}
You are doing it wrong, all Collections are serializable, in order to pass hashmap into intent you use
putExtra(String key, Serializable obj)
and to get the array back from intent, you do
getIntent().getSerializableExtra(String key)
Your Answer
btnsave = (Button) findViewById(R.id.btn_save);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent( getApplicationContext(), S.class );
intent.putExtra( "details", getData() );
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(MainActivity.this, "You have an ERROR", Toast.LENGTH_LONG).show();
}
}
});
public HashMap< String, List< String > > getData() {
HashMap< String, List< String > > expandableListDetail = new HashMap<>();
for ( int i = 2 ; i < container.getChildCount() ; i++ ) {
if ( container.getChildAt( i ) instanceof RelativeLayout ) {
List< String > childs = new ArrayList<>();
childs.add( ( ( TextView ) container.getChildAt( i ).findViewById( R.id.textout ) ).getText().toString() );
expandableListDetail.put( txtHeading.getText().toString(), childs );
}
}
return expandableListDetail;
}
You can do this by just following below instruction.
First Create class with implements Serializable as shown below.
public class DataWrapper implements Serializable{
private HashMap<String,List<String>> hasmap;
public DataWrapper(HashMap<String,List<String>> hasmap){
this.hasmap= hasmap;
}
public HashMap<String,List<String>> getHashMap(){
return this.hasmap;
}
}
In activity from where you want to pass HashMap<String,List<String>> put below code.
DataWrapper dw = new DataWrapper(expandableDataPump.getData());
Intent intent = new Intent(getApplicationContext(), ExpandableList.class);
intent.putExtra("details", dw);
startActivity(intent);
In your ExpandableList activity retrieve DataWrapper object and the retrieve your HashMap from that object as shown below.
try{
Intent intent = getIntent();
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("details");
HashMap<String,List<String>> hasmap = dw.getHashMap();
} catch(Exception e){
}
that's it. Its working for me.
Use
extras.putSerializable("HashMap",Hash_Map);
intent.putExtras(extras);
Instead of
intent.putStringArrayListExtra("details",(HashMap) expandableDataPump.getData());
btnsave = (Button) findViewById(R.id.btn_save);
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
expandableDataPump.getData();
Intent intent = new Intent(getApplicationContext(), ExpandableList.class);
intent.putExtra("details",(HashMap<String,>) expandableDataPump.getData());
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
Toast.makeText(MainActivity.this, "You have an ERROR", Toast.LENGTH_LONG).show();
}
}
});
}
To pass the HashMap,
btnsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(getApplicationContext(), ExpandableList.class);
intent.putExtra("details", expandableDataPump.getData());
startActivity(intent);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
To retrieve it in ExpandableList,
HashMap<String,List<String>> hashmap = (HashMap<String,List<String>>) getIntent().getSerializableExtra("details");
Related
I want to use onActivityResult method in Adapter but after searching on Stack Overflow I found I have to make interface for onActivityResult but I donot know how to make this and handle onActivityResult Methode to work as per my need.
Here is my Adapter Class.
public class PosterAdapter extends RecyclerView.Adapter<PosterAdapter.PosterViewHolder> {
private static final String TAG = "resPoster";
private ArrayList<Poster> posterArrayList;
private Context context;
public PosterAdapter(ArrayList<Poster> posterArrayList, Context context) {
this.posterArrayList = posterArrayList;
this.context = context;
}
#NonNull
#Override
public PosterViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.sending_image_layout, viewGroup, false);
return new PosterViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull PosterViewHolder posterViewHolder, int i) {
posterViewHolder.imageViewDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(posterViewHolder.relativeLayoutImage.getDrawingCache());
posterViewHolder.relativeLayoutImage.setDrawingCacheEnabled(false);
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/providers");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
Log.d(TAG,"filename: " + fileName);
File outFile = new File(dir, fileName);
Log.d(TAG,"outFile: " + outFile);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
posterViewHolder.imageViewEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
// startActivityForResult(i, 0);
((Activity) context).startActivityForResult(Intent.createChooser(i, "CHOOSING INTENT"), 0);
}
});
}
#Override
public int getItemCount() {
return posterArrayList.size();
}
public class PosterViewHolder extends RecyclerView.ViewHolder {
RelativeLayout relativeLayoutImage;
ImageView imageViewBg, imageViewEdit, imageViewDownload, imageViewShare;
CircleImageView imageViewProfie;
public PosterViewHolder(#NonNull View posterView) {
super(posterView);
relativeLayoutImage = posterView.findViewById(R.id.image_relative);
imageViewBg = posterView.findViewById(R.id.image_bg);
imageViewProfie = posterView.findViewById(R.id.image_profile_moving);
imageViewEdit = posterView.findViewById(R.id.edit_image);
imageViewDownload = posterView.findViewById(R.id.download_image);
imageViewShare = posterView.findViewById(R.id.share_image);
}
}
}
and I want to use this class
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 0) {
final Uri selectedUri = data.getData();
if (selectedUri != null) {
startCrop(selectedUri);
} else {
Toast.makeText(context, "Cannot retrieve selected Image", Toast.LENGTH_SHORT).show();
}
} else if (requestCode == UCrop.REQUEST_CROP) {
handleCropResult(data);
}
}
if (resultCode == UCrop.RESULT_ERROR) {
handleCropError(data);
}
}
Please Help me handle this method in interface.
Thank you.
**UPDATE: **
Here is my activity code to understand more my question.
RequestQueue requestQueue;
private ArrayList<Poster> posterArrayList = new ArrayList<>();
private RecyclerView recyclerView;
private PosterAdapter posterAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sending_image);
requestQueue = Volley.newRequestQueue(this);
recyclerView = findViewById(R.id.recycler_poster);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
getAllPoster();
}
private void getAllPoster() {
HashMap<String, String> params = new HashMap<String, String>();
params.put("poster_id", "1");
Log.d(TAG + "pp", String.valueOf(params));
String Url = Constants.Base_URL + "poster/";
JsonObjectRequest request = new JsonObjectRequest(Url, new JSONObject(params),
response -> {
Log.d("responsePending", String.valueOf(response));
try {
String statusResponseObject = response.getString("status");
String msgObject = response.getString("msg");
if (statusResponseObject.equals("200")){
JSONArray jsonArray = response.getJSONArray("response");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject pendingFragResponse = jsonArray.getJSONObject(i);
String posterObject = pendingFragResponse.getString("poster");
String positionObject = pendingFragResponse.getString("position");
String sizeObject = pendingFragResponse.getString("size");
String txt_positionObject = pendingFragResponse.getString("txt_position");
String titleObject = pendingFragResponse.getString("title");
String descriptionObject = pendingFragResponse.getString("description");
//
posterArrayList.add(new Poster(posterObject, positionObject,
sizeObject, txt_positionObject,
titleObject, descriptionObject));
posterAdapter = new PosterAdapter( posterArrayList, SendingImageActivity.this);
recyclerView.setAdapter(posterAdapter);
// wp10ProgressBar.hideProgressBar();
// wp10ProgressBar.setVisibility(View.GONE);
}
posterAdapter.notifyDataSetChanged();
// wp10ProgressBar.hideProgressBar();
}else {
// wp10ProgressBar.hideProgressBar();
// wp10ProgressBar.setVisibility(View.GONE);
Toast.makeText(SendingImageActivity.this, msgObject, Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
requestQueue.add(request);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
}
}, error -> {
error.printStackTrace();
Log.d(TAG + "error", String.valueOf(error.getMessage()));
Toast.makeText(this, "Server didn't response, Try after some time", Toast.LENGTH_LONG).show();
});
requestQueue.add(request);
}
}
Rather than using Interface pattern just create public method inside your adapter and call that method when your onActivityResult hits in Activity.
(This answer is just a workaround for your scenario. Ideally you should not pass your activity Context to your adapter, rather than use Interface pattern and receive callback inside your activity whenever any action took place (like clicking on edit button) inside your activity and pass relevant data while trigger callback from your adapter.)
You can refer AllNoteActivity and NoteAdapter for reference here
So what you need to do is put the current method onActivityResult() from PosterAdapter to the activity. Then make the methods startCrop(), handleCropResult() and handleCropError() public (I assume are in PosterAdapter).
In the onActivityResult() change the call of startCrop() to posterAdapter.startCrop(). Same for the other methods. And that should do it.
Create a method in adapter
In your adapter class
public void waterverYouWantMethod(){
}
And call that method from Activity when onActivityResult mehtod called.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
// call that method here
adapter.wateverYouWantMethod();
}
}
I am looking for some help with a tutorial I have been working on. I am trying to pass an object when I click on a list item from one activity to another using an Intent. I have posted some of the tutorial code I have been using below but can't seem to get it to work.
My Main Activity code is below:
StringRequest stringRequest = new StringRequest(Request.Method.GET, GET_HEROES_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i =0; i<array.length(); i++){
JSONObject obj = array.getJSONObject(i);
Hero hero = obj.getString("name"));
heroList.add(hero);
}
adapter = new HeroAdapter(heroList, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
And from my Adapter this is the code I have been using this:
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final Hero hero = heroList.get(position);
holder.textViewName.setText(hero.getName());
holder.textViewName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_ID, hero.getName());
context.startActivity(intent);
}
});
}
The intent is listed but it is not carrying the data into my new activity. I just want to take
hero.getName()
at the position it was clicked on in the itemlist and open up a new activity, and in the new activity set it to a TextView. This is part of code I have used on the new activity, but it wont post anything into the TextView.
TextView textViewName
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hero_detail);
textViewname = (textView) findViewById(R.id.textView);
Intent intent = getIntent();
if(intent == null)
return;
int id = intent.getIntExtra(HeroAdapter.KEY_HERO_ID, -1);
err.setText(id);
For instance I click on spiderman set in the list which is at position 3, and in the new activity the textView will load with Spiderman listed. Any help would be appreciated.
You can pass objects using serializable or parcelable interfaces but if you just want the name of your hero you should pass it as string in your intent. Now you're passing an id. You can totally do that. If it's int you should set it correctly to textview
err.setText(String.valueOf(id));
That's why it's not working now.
Or just pass it as string right from the beginning
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_NAME, hero.getName());
context.startActivity(intent);
And then retrieve it
Intent intent = getIntent();
if(intent == null)
return;
String heroName = intent.getStingExtra(HeroAdapter.KEY_HERO_NAME);
err.setText(heroName);
Try with this:
int id = -1;
if(getIntent().hasExtra(HeroAdapter.KEY_HERO_ID)){
id = getIntent().getExtras().getInt(HeroAdapter.KEY_HERO_ID);
}
err.setText("" + id);
If you need send the hero name then:
In your adapter:
Intent intent = new Intent(context, HeroDetailActivity.class);
intent.putExtra(KEY_HERO_ID, hero.getName());
context.startActivity(intent);
In your activity:
String heroName = "";
if(getIntent().hasExtra(HeroAdapter.KEY_HERO_ID)){
heroName = getIntent().getExtras().getString(HeroAdapter.KEY_HERO_ID);
}
err.setText(heroName);
I am new to android.
In my Activity class i get a link value by hitting an URL as below code.
try {
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("Sno");
String Tktid = jsonobject.getString("TKTID");
link = jsonobject.getString("Link");
List list = new List(jsonobject.getString("Sno"), jsonobject.getString("TKTID"),jsonobject.getString("Link"));
tktList.add(list);
Log.i("website content", name);
Log.i("website content", Tktid);
Log.i("website content", link);
}
//creating custom adapter object
ListViewAdapter adapter = new ListViewAdapter(tktList, getApplicationContext());
//adding the adapter to listview
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
And i am Assigning that value to a button in a Adapter class like below.
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewImageUrl);
Button btupdate = listViewItem.findViewById(R.id.btupdate);
List hero = tktList.get(position);
btupdate.setText(hero.getLink());
btupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mCtx, Main3Activity.class);
i.putExtra("Link",view.getId());
mCtx.startActivity(i);
}
});
Now here what my requirement is to Access that assigned link value in an other activity to retrieve some data related to that value.
Please hep me any one.
Use this:
btupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mCtx, Main3Activity.class);
i.putExtra("Link",btupdate.getText().toString().trim());
(or)
i.putExtra("Link",hero.getLink());
mCtx.startActivity(i);
}
});
Inside Main3Activity.java
Oncreate(){
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("Link");
}
}
you just replace this below code
TextView textViewName = listViewItem.findViewById(R.id.textViewName);
TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewImageUrl);
Button btupdate = listViewItem.findViewById(R.id.btupdate);
List hero = tktList.get(position);
btupdate.setText(hero.getLink());
btupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mCtx, Main3Activity.class);
i.putExtra("Link",hero.getLink());
mCtx.startActivity(i);
}
});
in my app i have a listview(asynctask) getting all the users from external database. Each row of my listview contains an image that the user can interact. When user presses that image i try to start a new intent by using the data that i already have(by using putExtra while starting the intent.) Listview works fine - it gathers all the data from database. But, the putExtra values are same for each row. I will appreciate if you can help me regarding that matter.
Code is as follows;
The important part is below
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
where i try to add putExtra.
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
//Invitation count
Integer inv = json.getInt("invitation");
setNotifCount(inv);
if(Integer.parseInt(res) == 1) {
// Getting JSON Array from URL
android1 = json.getJSONArray(TAG_LOCATIONDATA);
for (int i = 0; i < android1.length(); i++) {
JSONObject c = android1.getJSONObject(i);
// Storing JSON item in a Variable
final String ver = c.getString("username");
final String dataenlem = c.getString("enlem");
final String databoylam = c.getString("boylam");
final String datazaman = c.getString("zaman");
/*----------to get City-Name from coordinates ------------- */
StringBuffer address = new StringBuffer();
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(Double.parseDouble(dataenlem), Double.parseDouble(databoylam), 1);
if (addresses.size() > 0)
// System.out.println(addresses.get(0).getLocality());
address.append(addresses.get(0).getAddressLine(1))
.append(",").append(addresses.get(0).getAddressLine(2));
} catch (IOException e) {
e.printStackTrace();
}
String datalokasyon = address.toString();
/*----------to get City-Name from coordinates ------------- */
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put("enlem", dataenlem);
map.put("boylam", databoylam);
map.put("zaman", datazaman);
map.put("lokasyon", datalokasyon);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
BaseAdapter adapter = new SimpleAdapter(UserList.this, oslist,
R.layout.listview_userlist,
new String[]{TAG_VER,"zaman","lokasyon"}, new int[]{
R.id.vers,R.id.lastlocationinput,R.id.lastupdatedinput}) {
public View getView (int position, View convertView, ViewGroup parent)
{
View v = super.getView(position, convertView, parent);
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
showlastonmap.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent login = new Intent(getApplicationContext(),
HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", dataenlem);
login.putExtra("boylam", databoylam);
startActivity(login);
}
});
return v;
}
};
SwingBottomInAnimationAdapter animationAdapter = new SwingBottomInAnimationAdapter(adapter);
animationAdapter.setAbsListView(list);
list.setAdapter(animationAdapter);
}
//admob
interstitial.setAdListener(new AdListener() {
public void onAdLoaded() {
displayInterstitial();
}
});
//admob
}
if(Integer.parseInt(res) == 0) {
new SweetAlertDialog(UserList.this, SweetAlertDialog.ERROR_TYPE)
.setTitleText("Oops...")
.setContentText(getString(R.string.userlist_nofriend))
.show();
}
}
else {
return;
}
}catch
(JSONException e) {
e.printStackTrace();
}
}
}
you should do :
Intent login = new Intent(getApplicationContext(),
HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", oslist.get(position).get("enlem"));
login.putExtra("boylam", oslist.get(position).get("boylam"));
startActivity(login);
You have to create new object which contains required fields.
class Data {
String dataenlem;
String databoylam;
Data(String dataenlem, String databoylam) {
...
}
}
and then set corresponding to each row data using setTag method
ImageView showlastonmap = (ImageView)v.findViewById(R.id.showlastonmap);
// add this
showlastonmap.setTag(new Data(dataenlem, databoylam));
and get it on your onClick
public void onClick(View v) {
// and this
Data data = (Data)v.getTag();
Intent login = new Intent(getApplicationContext(),HaritaLastSolo.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
login.putExtra("enlem", data.dataenlem);
login.putExtra("boylam", data.databoylam);
startActivity(login);
}
I have four activities in my application A-->B-->C-->D.
I write a My own class MyActivity which extends Activity class. I write this class to handle activity stack.This class has two methods addActivitiyTostack() and getActivityFromStack()
I used a stack for storing activities.
All other activities are extends this class.
When I moved from one activity to other using intent it added to stack.
And when I moved backword activity gets popped up.
I can correctly add activities to stack, But I have problem in popping the activities.
also I have Logout Button on all activities, OnClick of this button I want to close the application how to implement it? Anybody know how to handle activity stack in Android.
This is my code.
package com.example.iprotect;
import java.util.Enumeration;
import java.util.Stack;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MyActivity extends Activity {
private static Stack<Activity> stack = new Stack<Activity>();
static int top=0;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addActivityToStack(this);
}
public static void addActivityToStack(MyActivity myActivity) {
// TODO Auto-generated method stub
stack.push(myActivity);
for (int i =0; i< stack.size() ; i++) {
Activity act=stack.get(i);
Log.i("Element in stack", ""+act);
}
}
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
//getActivityFromStack();
//logoutFromApplication();
}
public static void logoutFromApplication() {
// TODO Auto-generated method stub
Enumeration<Activity> enm=stack.elements();
while(enm.hasMoreElements())
{
Activity act=enm.nextElement();
stack.pop();
}
}
public static Activity getActivityFromStack() {
return stack.pop();
}
}
A-->
public class WebServiceActivity extends MyActivity{
EditText editText1, editText2;
Button button;
String response = "";
String email, password;
public final Pattern EMAIL_ADDRESS_PATTERN = Pattern
.compile(".+#.+\\.[a-z]+");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editText1 = (EditText) findViewById(R.id.etEmail);
final EditText editText2 = (EditText) findViewById(R.id.etPassword);
button = (Button) findViewById(R.id.loginButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText1.getText().toString())) {
Toast.makeText(getApplicationContext(),
"please enter email id", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(editText2.getText().toString())) {
Toast.makeText(getApplicationContext(),
"please enter passwod", Toast.LENGTH_SHORT).show();
} else {
Boolean bool = EMAIL_ADDRESS_PATTERN.matcher(
editText1.getText().toString()).matches();
if (bool == true) {
} else {
Toast.makeText(getApplicationContext(),
"Invalid email id", Toast.LENGTH_SHORT).show();
}
email = editText1.getText().toString();
password = editText2.getText().toString();
// final ProgressDialog pd = ProgressDialog.show(
// WebServiceActivity.this, "Calling webservice...",
// "Please wait...", true, false);
final ProgressBar bar = (ProgressBar) findViewById(R.id.progressBar2);
bar.setVisibility(View.VISIBLE);
new AsyncTask<Void, Void, Void>() {
String r;
protected void onPreExecute() {
};
#Override
protected Void doInBackground(Void... params) {
r = invokeWebService();
return null;
};
protected void onPostExecute(Void result) {
bar.setVisibility(View.VISIBLE);
};
}.execute();
}
}
private String invokeWebService() {
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
Map<String, String> params = new HashMap<String, String>();
params.put("action", "auth");
params.put("email", email);
params.put("password", password);
response = webService.WebGet("auth", params);
JSONObject jsonObject = new JSONObject(response);
String rr = jsonObject.optString("status");
if (TextUtils.equals(rr, "success")) {
Log.e("MSG", "status==success");
Intent intent = new Intent(WebServiceActivity.this,
SecondActivity.class);
//MyActivity.addActivityToStack(WebServiceActivity.this);
intent.putExtra("email", email);
intent.putExtra("password", password);
WebServiceActivity.this.startActivity(intent);
finish();
} else {
Log.e("MSG", "status ==failed");
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
});
}
}
B-->
public class SecondActivity extends MyActivity {
ListView listView;
String email1, password1;
ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
String r;
String r1;
String tablename;
String rows;
JSONObject jsonObject;
String tablename2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
Intent intent = getIntent();
email1 = intent.getExtras().getString("email");
password1 = intent.getExtras().getString("password");
Button btn1 = (Button) findViewById(R.id.refreshbutton);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
SecondActivity.this, "Refresh List...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
r = invokeWebService();
return null;
}
protected void onPostExecute(Void result) {
};
}.execute();
}
});
Button btn = (Button) findViewById(R.id.logoutbutton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
SecondActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(SecondActivity.this,
WebServiceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
SecondActivity.this.startActivity(intent);
}
}.execute();
}
});
listView = (ListView) findViewById(R.id.listview1);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
JSONStructure jsonstructure = (JSONStructure) listView
.getAdapter().getItem(position);
final String tablename1 = jsonstructure.getTableName()
.toString();
Intent intent = new Intent(SecondActivity.this,
ProgressBarActivity.class);
//MyActivity.addActivityToStack(SecondActivity.this);
intent.putExtra("tablename", tablename1);
intent.putExtra("Rows", rows);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
SecondActivity.this.startActivity(intent);
}
});
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
r = invokeWebService();
try {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject(r);
jsonArray = jsonObject.getJSONArray("Records");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
tablename = c.optString("TABLE NAME");
rows = c.optString("Rows");
JSONStructure jsonStructure = new JSONStructure();
jsonStructure.setTableName(tablename);
jsonStructure.setRows(rows);
arrayList.add(jsonStructure);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (arrayList != null && arrayList.size() > 0) {
MyAdapter adapter = new MyAdapter(SecondActivity.this,
arrayList);
listView.setAdapter(adapter);
}
}
}.execute();
}
private String invokeWebService() {
String response = "";
try {
WebService webService = new WebService(
"http://sphinx-solution.com/iProtect/api.php?");
Map<String, String> params = new HashMap<String, String>();
params.put("action", "getTables");
params.put("email", email1);
params.put("password", password1);
response = webService.WebGet("getTables", params);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
C-->
public class ThirdActivity extends MyActivity {
String tablename1, row1, json1;
ArrayList<JSONStructure> arrayList = new ArrayList<JSONStructure>();
JSONArray jsonArray, jsonArray2;
JSONObject jsonObject;
String row;
String email1, password1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.third_layout);
ListView listView = (ListView) findViewById(R.id.listview2);
TextView textView = (TextView) findViewById(R.id.title_textview);
Intent intent = getIntent();
tablename1 = intent.getExtras().getString("tablename");
row = intent.getExtras().getString("Rows");
textView.setText(tablename1);
json1 = intent.getExtras().getString("Json");
email1 = intent.getExtras().getString("email");
password1 = intent.getExtras().getString("password");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
Button button = (Button) findViewById(R.id.goback);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ThirdActivity.this,
SecondActivity.class);
MyActivity.getActivityFromStack();
intent.putExtra("email", email1);
intent.putExtra("password", password1);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ThirdActivity.this.startActivity(intent);
}
});
}
}.execute();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
final int position, long id) {
final ProgressDialog pd = ProgressDialog.show(
ThirdActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... paramArrayOfParams) {
pd.dismiss();
try {
jsonObject = new JSONObject(json1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(ThirdActivity.this,
FinalActivity.class);
//MyActivity.addActivityToStack(ThirdActivity.this);
intent.putExtra("tablename", tablename1);
intent.putExtra("Json", jsonObject.toString());
intent.putExtra("Row", position);
intent.putExtra("email", email1);
intent.putExtra("password", password1);
ThirdActivity.this.startActivity(intent);
}
}.execute();
}
});
try {
JSONObject jsonObject = new JSONObject(json1);
JSONArray jsonArray = new JSONArray();
jsonArray = jsonObject.getJSONArray("FirstThree");
jsonArray2 = jsonObject.getJSONArray("Color");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String one = c.optString("One");
String two = c.optString("Two");
String three = c.optString("Three");
JSONObject c1 = jsonArray2.getJSONObject(i);
String color = c1.optString("color");
JSONStructure jsonStructure = new JSONStructure();
jsonStructure.column1 = one;
jsonStructure.column2 = two;
jsonStructure.column3 = three;
jsonStructure.setColumn1(one);
jsonStructure.setColumn2(two);
jsonStructure.setColumn3(three);
jsonStructure.setColor(color);
arrayList.add(jsonStructure);
Log.e("one", c.optString("One"));
Log.e("two", c.optString("Two"));
Log.e("three", c.optString("Three"));
Log.e("color", c1.optString("color"));
}
} catch (Exception e) {
e.printStackTrace();
}
if (arrayList != null && arrayList.size() > 0) {
MyAdapter1 adapter1 = new MyAdapter1(ThirdActivity.this, arrayList);
listView.setAdapter(adapter1);
}
Button btn = (Button) findViewById(R.id.logoutbutton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog pd = ProgressDialog.show(
ThirdActivity.this, "Calling webservice...",
"Please wait...", true, false);
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
pd.dismiss();
return null;
}
#Override
protected void onPostExecute(Void result) {
Intent intent = new Intent(ThirdActivity.this,
WebServiceActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
ThirdActivity.this.startActivity(intent);
super.onPostExecute(result);
}
}.execute();
}
});
}
}
Assuming you need this stack solely for the logout function, there are better ways. Use a broadcast instead. Register a BroadcastReceiver in MyActivity.onCreate. The receiver should just call the activity's finish(). Send the broadcast from the button's click listener (btn1? What does that button do? Couldn't guess from the name; better names required ;) ). That's it.