Android Async Task freeze the UI - android

Hi I have an Activity which user open upon click on a TAB. Actually I have a ViewGroup and Tabactivity as Main Activity. on the first tab I have three activity.
Now in an activity I have a list view (custom) populating on Oncreate and a ViewFlipper (only adding view) in Onresume using AsyncTask.
In that asynctask in Pre Execute if I add code for loader it gives error. Also If I do not show the loader the screen is freezing until the Async task finished.
I actually want to load the list view first and then in background run the async task with a loader. Also does not want to freeze the screen.
Here Is My Acivity
package thai.phrasi.ctech.com.phrasi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import com.squareup.picasso.Picasso;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class WordActivity extends ActionBarActivity {
categories category_obj;
word word_obj;
wordDB wordDb;
WordAdapter adapter;
MediaPlayer mPlayer;
boolean doubleBackToExitPressedOnce = false;
public static ViewFlipper viewFlipper;
public View view;
private static ProgressDialog pleaseWaitDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_word);
viewFlipper = new ViewFlipper(this);
viewFlipper.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TextView txt = (TextView) findViewById(R.id.phraseListHeading);
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
String categoryName = getIntent().getExtras().getString("categoryName").toUpperCase();
wordDb = new wordDB(getApplicationContext());
getAllWords();
//asyncLoadWordList task2 = new asyncLoadWordList(getApplicationContext());
//task2.execute();
txt.setTypeface(font);
txt.setText(categoryName);
ListView wordListView;
wordListView = (ListView)findViewById(R.id.list_view_word);
wordListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object o = parent.getItemAtPosition(position);
word_obj = (word) o;
if(Integer.valueOf(word_obj.getCategoryId())>=0) {
Intent myIntent = new Intent(WordActivity.this, WordDetailsActivity.class);
myIntent.putExtra("word_obj", word_obj);
myIntent.putExtra("position",position);
myIntent.putExtra("currentClickedId", word_obj.getCsvWordId().toString());
myIntent.putExtra("favouriteFlag",0);
myIntent.putExtra("searchFlag",0);
myIntent.putExtra("searchString", "");
WordActivity.this.startActivity(myIntent);
}
}
});
ImageView backButton = (ImageView) findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent backIntent = new Intent(WordActivity.this, CategoryActivity.class);
View vw = FirstGroup.group.getLocalActivityManager().startActivity("CategoryActivity", backIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
FirstGroup.group.replaceView(vw);
viewFlipper.removeAllViews();
System.runFinalization();
Runtime.getRuntime().gc();
System.gc();
}
});
}
#Override
protected void onPause() {
super.onPause(); // Don't forget this line
stop();
}
public void stop(){
mPlayer=adapter.getMPlayerInstace();
if(mPlayer!=null){
mPlayer.stop();
mPlayer.release();
}
}
#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_word, 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);
}
protected void onResume(){
super.onResume();
new Thread(new Runnable() {
public void run(){
//All your heavy stuff here!!!
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
if(viewFlipper.getChildCount() == 0) {
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
}).start();
}
public void getAllWords(){
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5), row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
adapter = new WordAdapter(WordActivity.this, words);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
//Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Double tap back button to exit.");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_HORIZONTAL, 0, 0);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
public class asyncLoadWordList extends AsyncTask<ArrayList<word>, Void, ArrayList<word>>{
private Context mContext;
public asyncLoadWordList(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
/* if (pleaseWaitDialog == null)
pleaseWaitDialog= ProgressDialog.show(WordActivity.this,
"PLEASE WAIT",
"Getting results...",
false);
*/
}
#Override
protected ArrayList<word> doInBackground(ArrayList<word>... params) {
wordDb = new wordDB(mContext);
category_obj = (categories) getIntent().getSerializableExtra("category_obj");
ArrayList<word> words = new ArrayList<word>();
Cursor row = wordDb.selectWordList(category_obj.getCsvCategoryId().toString());
words.add(new word("-1", "-1", "", "", "", "", "", "", "x.mp3", ""));
words.add(new word("-2", "-2", "", "", "", "", "", "", "x.mp3", ""));
row.moveToFirst();
while (!row.isAfterLast()) {
//Log.d("Data id: ", row.getString(2));
words.add( new word(row.getString(0),row.getString(1),row.getString(2),row.getString(3),row.getString(4),row.getString(5),row.getString(6),row.getString(7),row.getString(8),row.getString(9)));
row.moveToNext();
}
row.close();
return words;
}
protected void onPostExecute(ArrayList<word> result) {
adapter = new WordAdapter(WordActivity.this, result);
ListView listView = (ListView) findViewById(R.id.list_view_word);
listView.setAdapter(adapter);
if (pleaseWaitDialog != null) {
pleaseWaitDialog.dismiss();
pleaseWaitDialog = null;
}
asyncFlipperView task = new asyncFlipperView(getApplicationContext());
task.execute(new String[]{category_obj.getCsvCategoryId().toString()});
}
}
public class asyncFlipperView extends AsyncTask<String, Void, String[]> {
String categoryId;
private Context mContext;
wordDB wordDb;
Cursor row;
JSONObject json;
View view;
//private ProgressDialog dialog = new ProgressDialog(WordActivity.this);
public asyncFlipperView(Context context) {
mContext = context;
}
protected void onPreExecute() {
//Start the splash screen dialog
}
#Override
protected String[] doInBackground(String... params) {
categoryId = params[0];
json = new JSONObject();
/*do application level task*/
GlobalState state = ((GlobalState) mContext);
state.doAction();
/*Ends*/
wordDb = new wordDB(mContext);
row = wordDb.selectWordList(categoryId);
Log.d("Tag: search result", row.getString(2).toString());
return new String[]{categoryId};
}
protected void onPostExecute(String[] result) {
categoryId = result[0];
ImageView phraseImage = null;
Typeface font = Typeface.createFromAsset(WordActivity.this.getAssets(), "fonts/NotoSans-Regular.ttf");
row.moveToFirst();
while (!row.isAfterLast()) {
/*phrase Image*/
Integer fileNameLength = row.getString(5).toString().length();
String fileName = row.getString(5).toString();
String imageFile = fileName.substring(0, fileNameLength - 4);
//viewFlipper = (ViewFlipper)findViewById(R.id.flipper);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.word_details_flipper_view, null);
TextView tv = (TextView) view.findViewById(R.id.text_english);
tv.setTypeface(font);
tv.setText(row.getString(2).toString());
String picName = row.getString(6).toString();
picName = picName.replace(".png", "");
Uri url1 = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + picName);
ImageView backgroundImage = (ImageView) view.findViewById(R.id.backgroundImage);
Picasso.with(mContext).load(url1).fit().centerCrop().into(backgroundImage);
TextView tvTranslated = (TextView) view.findViewById(R.id.translated_phrase);
tvTranslated.setTypeface(font);
tvTranslated.setText(row.getString(3).toString());
TextView pronounce = (TextView) view.findViewById(R.id.pronounce);
pronounce.setTypeface(font);
pronounce.setText(row.getString(4).toString());
phraseImage = (ImageView) view.findViewById(R.id.phrase_image);
Uri url = Uri.parse("android.resource://" + mContext.getPackageName() + "/drawable/" + imageFile);
Picasso.with(mContext).load(url).resize(576, 888).into(phraseImage);
view.setTag(R.string.csvId, row.getString(0).toString());
viewFlipper.addView(view);
row.moveToNext();
}
row.close();
}
private Context getDialogContext() {
Context context;
if (getParent() != null) context = getParent();
else context = WordActivity.this;
return context;
}
}
}

Related

Convert to AnsyncTask Android

I am new to Android development, I am working on a App and I want to convert my below mentioned code to AnsyncTask. Because it is showing me Run-time error that I am doing too much work on UI thread. Please help me to convert it to AnsyncTask.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for(int i=1; i<=strLength; i++){
if(i == 2){
dash = dash+Character.toString(randomStr.charAt(1));
} else if (i == 5){
dash = dash+ Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter (getApplicationContext(),android.R.layout.simple_list_item_1,array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String finalDisplayVal = displayVal;
int count = 0;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if(randomStr.contains(itemValue)){ // If selected alphabets exists in string
for(int k=0; k<strLength; k++){
if(Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)){
int charPos = randomStr.indexOf(itemValue);
while(charPos >= 0){
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4-count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if(count > 3) {
Toast.makeText(PlayActivity.this, "You Loose, Value is: "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount(){
if(randomStr.equalsIgnoreCase(finalDisplayVal)){
Toast.makeText(PlayActivity.this, "Hurray!!! You WIN... It's "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
});
}
}
AsyncTask Code;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity1 extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
int count = 0;
String randomStr;
String finalDisplayVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for (int i = 1; i <= strLength; i++) {
if (i == 2) {
dash = dash + Character.toString(randomStr.charAt(1));
} else if (i == 5) {
dash = dash + Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String finalDisplayVal = displayVal;
runner.execute(finalDisplayVal);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if (randomStr.contains(itemValue)) { // If selected alphabets exists in string
for (int k = 0; k < strLength; k++) {
if (Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)) {
int charPos = randomStr.indexOf(itemValue);
while (charPos >= 0) {
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4 - count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
});
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if (count > 3) {
Toast.makeText(PlayActivity1.this, "You Loose, Value is: " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount() {
if (randomStr.equalsIgnoreCase(finalDisplayVal)) {
Toast.makeText(PlayActivity1.this, "Hurray!!! You WIN... It's " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, ProgressDialog> {
#Override
protected ProgressDialog doInBackground(String... params) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity1.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
try {
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
}catch (Exception e){
e.printStackTrace();
}
return mProgressDialog;
}
}
}

Not getting hashmap from bundle - Android

I want to get HashMap which is being passed through Bundle from a AsyncTask. But I am getting NullPointerException.
Flow is like below...
FragmentMainActivity -> TableScreenSectionwiseActivity -> GetSectionsAsync
HashMap is passed from GetSectionsAsync to TableScreenSectionwiseActivity through Bundle.
Note: FragmentMainActivity is FragmentActivity.TableScreenSectionwiseActivity is Fragment.GetSectionsAsync is a AsyncTask.
What I have tried, is like below.
Error I getting...
Error Image
TableScreenSectionwiseActivity.java
package com.malaka.ui;
import java.util.ArrayList;
import java.util.HashMap;
import adapters.table_section_adapter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.malaka.R;
import com.malaka.helper.ActionItem;
import com.malaka.helper.GetSectionsGetterSetter;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.GetSectionsAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.utils.PreferenceUtils;
public class TableScreenSectionwiseActivity extends Fragment implements
OnItemClickListener {
final static String TAG = "TableScreenSectionwiseActivity";
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
String[] values = new String[] { "1", "2" };
public static FragmentActivity activity;
RelativeLayout rl;
static PreferenceUtils pref;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
HashMap<String, ArrayList<String>> map1;
ArrayList<String> ids, names;
ListView section_list;
TextView version, malaka;
ImageView refresh;
Animation rotation;
private TextView mDropdownTitle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.table_screen_sectionwise,
container, false);
init(view);
return view;
}
private void init(View view) {
activity = getActivity();
pref = new PreferenceUtils(getActivity());
malaka = (TextView) view
.findViewById(R.id.txt_malaka_title_table_sectionwise);
malaka.setText(pref.getLocation());
if (!pref.getSectionStatus()) {
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Bundle bundle = new Bundle();
Log.e("Bundle Size: ", bundle.size() + "");
map1 = (HashMap<String, ArrayList<String>>) getArguments()
.getSerializable("SECTIONS_HASHMAP");
GetSectionsGetterSetter.setData(map1);
ids = map1.get("ID_LIST");
names = map1.get("NAME_LIST");
for (int i = 0; i < names.size(); i++) {
Log.e("Names: ", names.get(i));
}
section_list = (ListView) view
.findViewById(R.id.section_name_list_view);
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), values);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
rl = (RelativeLayout) view.findViewById(R.id.ll_location_sectionwise);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
quickActionLocation.show(arg0);
}
});
version = (TextView) view.findViewById(R.id.table_version_sectionwise);
version.setText(pref.getVersion());
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
refresh = (ImageView) view
.findViewById(R.id.img_refresh_table_sectionwise);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
refresh.startAnimation(rotation);
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
});
ActionItem tableItem = new ActionItem(ID_TABLE, "Table Status");
ActionItem taskItem = new ActionItem(ID_TASK, "My Tasks");
ActionItem managerItem = new ActionItem(ID_MANAGER, "Manager");
ActionItem recipeItem = new ActionItem(ID_RECIPE, "Recipes");
ActionItem instItem = new ActionItem(ID_INSTRUCTION, "Instructions");
ActionItem searchItem = new ActionItem(ID_SEARCH, "Search");
ActionItem helpItem = new ActionItem(ID_HELP, "Help");
ActionItem settingItem = new ActionItem(ID_SETTING, "Settings");
ActionItem logoutItem = new ActionItem(ID_LOGOUT, "Logout");
ActionItem kpItem = new ActionItem(ID_KP, "Koregaon Park");
ActionItem cityItem = new ActionItem(ID_CITY, "Phoneix Market");
ActionItem banerItem = new ActionItem(ID_BANER, "Baner");
quickActionLocation = new QuickActionLocation(getActivity(),
QuickActionLocation.VERTICAL);
quickActionLocation.addActionItem(kpItem, Color.WHITE);
quickActionLocation.addActionItem(cityItem, Color.WHITE);
quickActionLocation.addActionItem(banerItem, Color.WHITE);
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
// tableItem.setSticky(true);
// create QuickAction. Use QuickAction.VERTICAL or
// QuickAction.HORIZONTAL param to define layout
// orientation
quickAction = new QuickAction(getActivity(), QuickAction.VERTICAL);
// add action items into QuickAction
quickAction.addActionItem(tableItem, Color.WHITE);
quickAction.addActionItem(taskItem, Color.parseColor("#F2A523"));
if (pref.getUserRole()) {
quickAction.addActionItem(managerItem, Color.parseColor("#F2A523"));
}
if (pref.getRecipeScreenStatus()) {
quickAction.addActionItem(recipeItem, Color.parseColor("#F2A523"));
}
quickAction.addActionItem(instItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(searchItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(helpItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(settingItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(logoutItem, Color.parseColor("#F2A523"));
// Set listener for action item clicked
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
quickAction.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_TABLE) {
closeDropdown();
} else if (actionId == ID_TASK) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new TaskLeadingActivity(), "left");
} else if (actionId == ID_MANAGER) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ManagerPageActivity(), "left");
} else if (actionId == ID_RECIPE) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ReceipiesScreenActivity(), "left");
} else if (actionId == ID_INSTRUCTION) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new InstructionActivity(), "left");
} else if (actionId == ID_SEARCH) {
closeDropdown();
} else if (actionId == ID_HELP) {
closeDropdown();
} else if (actionId == ID_SETTING) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new SettingScreenActivity(), "left");
} else if (actionId == ID_LOGOUT) {
closeDropdown();
Logout logout = new Logout(getActivity());
}
}
});
// set listnener for on dismiss event, this listener will be called only
// if QuickAction dialog was dismissed
// by clicking the area outside the dialog.
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
// Toast.makeText(getActivity(), "Dismissed",
// Toast.LENGTH_SHORT).show();
closeDropdown();
}
});
// Set listener for action item clicked
quickActionLocation
.setOnActionItemClickListener(new QuickActionLocation.OnActionItemClickListener() {
#Override
public void onItemClick(QuickActionLocation source,
int pos, int actionId) {
ActionItem actionItem = quickActionLocation
.getActionItem(pos);
quickActionLocation.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_KP) {
getTableStatus("Koregaon Park");
} else if (actionId == ID_CITY) {
getTableStatus("Phoneix Market City");
} else if (actionId == ID_BANER) {
getTableStatus("Baner");
}
}
});
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
}
public void getTableStatus(String location) {
pref.setLocation(location);
Log.e(TAG, "location : " + pref.getLocation());
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
private void openDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_up, 0);
}
private void closeDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_down, 0);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(activity, "Clicked" + position, Toast.LENGTH_SHORT)
.show();
}
}
GetSectionsAsync.java
package com.malaka.helper.async;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.CustomerDetailsActivity;
import com.malaka.ui.TableScreenSectionwiseActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class GetSectionsAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "GetSectionsAsync";
FragmentActivity context;
String xml;
HashMap<String, ArrayList<String>> details;
PreferenceUtils pref;
int response;
boolean isConnected;
public GetSectionsAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.GetSecNAMESPACE,
AsyncAttributes.GetSecMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
PropertyInfo pi = new PropertyInfo();
pi.setName("RLocation");
pi.setValue(map.get("Location_Name"));
pi.setType(String.class);
request.addProperty(pi);
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.e(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.GetSecURL);
try {
androidHttpTransport.call(AsyncAttributes.GetSecSOAP_ACTION,
envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetSectionsForLocationResponse{GetSectionsForLocationResult=Failur; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.e(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.e(TAG, "Task 1 result " + xml);
details = TableStatusXmlParser.getSectionsXml(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus(true);
goAhead();
}
}
private void goAhead() {
Bundle bundle = new Bundle();
bundle.putSerializable("SECTIONS_HASHMAP", details);
Fragment fragment = new TableScreenSectionwiseActivity();
fragment.setArguments(bundle);
ReplaceFragment.getReplaceFragment(context, fragment, "");
}
}
If you guys want FragmentMainActivity code. I can put it. But I dont think so it is required. Thanks in advance.
At the end I have achieved it through INTERFACE.
Just do like below...
Make interface in GetSectionsAsync.java named FragmentInterfaceCallBack and declare a method named onTaskCompleted().
Now define a method in GetSectionsAsync.java named setFragmentInterfaceCallBack which will set the interface's object while calling from TableScreenSectionwiseActivity.java.
Now in onPostExecute method write below code....interfaceCallBack.onTaskCompleted(details); details is a data received from web service.
Go to TableScreenSectionwiseActivity.java and implements FragmentInterfaceCallBack, define it's onTaskCompleted() method and add below code to TableScreenSectionwiseActivity.java where you are calling AsyncTask getSectionsAsync.setFragmentInterfaceCallBack(this); where getSectionsAsync is a object of GetSectionsAsync.java.
In onTaskCompleted() method you get your desire data.
I have made below changes in my both files.
GetSectionsAsync.java
Making interface and defining setFragmentInterfaceCallBack() method....
private FragmentInterfaceCallBack interfaceCallBack;
public interface FragmentInterfaceCallBack {
public void onTaskCompleted(HashMap<String, ArrayList<String>> map);
}
public void setFragmentInterfaceCallBack(
FragmentInterfaceCallBack _interfaceCallBack) {
this.interfaceCallBack = _interfaceCallBack;
}
In onPostExecute method....
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus1(true);
// goAhead();
}
interfaceCallBack.onTaskCompleted(details);
}
TableScreenSectionwiseActivity.java
Implementing interface....
public class TableScreenSectionwiseActivity extends Fragment implements OnItemClickListener, FragmentInterfaceCallBack {
Calling AsyncTask....
if (!pref.getSectionStatus1()) {
Log.e("Once Again in TableScreenSectionwiseActivity: ", "hmm....");
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
getSectionsAsync.setFragmentInterfaceCallBack(this);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Defining interface's method....
#Override
public void onTaskCompleted(HashMap<String, ArrayList<String>> hashMap) {
ids = hashMap.get("ID_LIST");
names = hashMap.get("NAME_LIST");
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), names, ids);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
}
That's it. Hope this will help someone..
Map<String, String> map = ((Bundle)appRestrictions.get(key)).keySet().stream().collect(Collectors.toMap(x -> x, x -> bundle.get(x).toString()));
JSONObject jsonNested = new JSONObject(map);

How do I reuse the image that is already imported to the detail view of this RSS Fragment

I have this code that receives the RSS feed and displays it into a Row, however, it does not carry over the image once the row has been clicked. How do I achieve this image transfer from the list view to the detailed view.
This is the RSS Reader View
package com.sieae.jamaicaobserver.rss.ui;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
* This activity is used to display a list of rss items
*/
public class RssFragment extends Fragment {
private RSSFeed myRssFeed = null;
private Activity mAct;
private LinearLayout ll;
private RelativeLayout pDialog;
public class MyCustomAdapter extends ArrayAdapter<RSSItem> {
public MyCustomAdapter(Context context, int textViewResourceId,
List<RSSItem> list) {
super(context, textViewResourceId, list);
}
#SuppressLint("InflateParams")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final ViewHolder holder;
if(row==null){
LayoutInflater inflater=mAct.getLayoutInflater();
row=inflater.inflate(R.layout.fragment_rss_row, null);
holder = new ViewHolder();
holder.listTitle=(TextView)row.findViewById(R.id.listtitle);
holder.listPubdate=(TextView)row.findViewById(R.id.listpubdate);
holder.listDescription=(TextView)row.findViewById(R.id.shortdescription);
holder.listThumb =(ImageView)row.findViewById(R.id.listthumb);
row.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.listTitle.setText(myRssFeed.getList().get(position).getTitle());
holder.listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
String html = myRssFeed.getList().get(position).getRowDescription();
holder.listDescription.setText(html);
holder.listThumb.setImageDrawable(null);
//get Imageloader
ImageLoader imageLoader = Helper.initializeImageLoader(mAct);
//LayoutInflater inflater = (LayoutInflater) mAct
// .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View v = inflater.inflate(R.layout.fragment_rss, null);
//ListView listView = (ListView) v.findViewById(R.id.rsslist);
//pausing on scrolling the listview
//boolean pauseOnScroll = true; // or true
//boolean pauseOnFling = true; // or false
//PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
//listView.setOnScrollListener(listener);
String thumburl = myRssFeed.getList().get(position).getThumburl();
if (thumburl != "" && thumburl != null){
//setting the image
imageLoader.displayImage(myRssFeed.getList().get(position).getThumburl(), holder.listThumb, new SimpleImageLoadingListener() {
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
if (10 > loadedImage.getWidth() || 10 > loadedImage.getHeight()) {
// handle scaling
holder.listThumb.setVisibility(View.GONE);
} else {
holder.listThumb.setVisibility(View.VISIBLE);
}
}
});
} else {
holder.listThumb.setVisibility(View.GONE);
}
return row;
}
}
static class ViewHolder {
TextView listTitle;
TextView listPubdate;
TextView listDescription;
ImageView listThumb;
int position;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ll = (LinearLayout) inflater.inflate(R.layout.fragment_rss, container, false);
setHasOptionsMenu(true);
if ((getResources().getString(R.string.ad_visibility).equals("0"))){
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) ll.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
return ll;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mAct = getActivity();
Log.v("INFO", "onAttach() called");
new MyTask().execute();
}
private class MyTask extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute(){
pDialog = (RelativeLayout) ll.findViewById(R.id.progressBarHolder);
}
#Override
protected Void doInBackground(Void... arg0) {
try {
String weburl = RssFragment.this.getArguments().getString(MainActivity.DATA);
URL rssUrl = new URL(weburl);
SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
XMLReader myXMLReader = mySAXParser.getXMLReader();
RSSHandler myRSSHandler = new RSSHandler();
myXMLReader.setContentHandler(myRSSHandler);
InputSource myInputSource = new InputSource(rssUrl.openStream());
myXMLReader.parse(myInputSource);
myRssFeed = myRSSHandler.getFeed();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView listview = (ListView) ll.findViewById(R.id.rsslist);
if (myRssFeed != null) {
MyCustomAdapter adapter = new MyCustomAdapter(mAct,
R.layout.fragment_rss_row, myRssFeed.getList());
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
Intent intent = new Intent(mAct,
RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed
.getItem(position).getTitle());
bundle.putString("keyDescription",
myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position)
.getLink());
bundle.putString("keyPubdate",
myRssFeed.getItem(position).getPubdate());
bundle.putString("keyThumburl",
myRssFeed.getItem(position).getThumburl());
intent.putExtras(bundle);
startActivity(intent);
}
});
} else {
Helper.noConnection(mAct, true);
}
if (pDialog.getVisibility() == View.VISIBLE) {
pDialog.setVisibility(View.GONE);
//feedListView.setVisibility(View.VISIBLE);
Helper.revealView(listview,ll);
}
super.onPostExecute(result);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.rss_menu, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh_rss:
new MyTask().execute();
return true;
case R.id.info:
//show information about the feed in general in a dialog
if (myRssFeed!=null)
{
String FeedTitle = (myRssFeed.getTitle());
String FeedDescription = (myRssFeed.getDescription());
//String FeedPubdate = (myRssFeed.getPubdate()); most times not present
String FeedLink = (myRssFeed.getLink());
AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
String titlevalue = getResources().getString(R.string.feed_title_value);
String descriptionvalue = getResources().getString(R.string.feed_description_value);
String linkvalue = getResources().getString(R.string.feed_link_value);
if (FeedLink.equals("")){
builder.setMessage(titlevalue+": \n"+FeedTitle+
"\n\n"+descriptionvalue+": \n"+FeedDescription);
} else {
builder.setMessage(titlevalue+": \n"+FeedTitle+
"\n\n"+descriptionvalue+": \n"+FeedDescription +
"\n\n"+linkvalue+": \n"+FeedLink);
};
builder.setNegativeButton(getResources().getString(R.string.ok),null)
.setCancelable(true);
builder.create();
builder.show();
}else{
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
This is the detailed view
package com.sieae.jamaicaobserver.rss.ui;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.sieae.jamaicaobserver.R;
import com.sieae.jamaicaobserver.fav.FavDbAdapter;
import com.sieae.jamaicaobserver.util.WebHelper;
import com.sieae.jamaicaobserver.web.WebviewActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/**
* This activity is used to display details of a rss item
*/
public class RssDetailActivity extends ActionBarActivity {
private WebView wb;
private FavDbAdapter mDbHelper;
private Toolbar mToolbar;
String date;
String link;
String title;
String description;
String favorite;
String listThumb;
#SuppressLint("SetJavaScriptEnabled")#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_details);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
TextView detailsTitle = (TextView) findViewById(R.id.detailstitle);
TextView detailsPubdate = (TextView) findViewById(R.id.detailspubdate);
Bundle bundle = this.getIntent().getExtras();
detailsTitle.setText(bundle.getString("keyTitle"));
detailsPubdate.setText(bundle.getString("keyPubdate"));
date = (bundle.getString("keyPubdate"));
link = (bundle.getString("keyLink"));
title = (bundle.getString("keyTitle"));
description = (bundle.getString("keyDescription"));
favorite = (bundle.getString("keyFavorites"));
listThumb = (bundle.getString("keyThumburl"));
wb = (WebView) findViewById(R.id.descriptionwebview);
//parse the html and apply some styles
Document doc = Jsoup.parse(description);
String html = WebHelper.docToBetterHTML(doc, this);;
wb.getSettings().setJavaScriptEnabled(true);
wb.loadDataWithBaseURL(link, html , "text/html", "UTF-8", "");
Log.v("INFO", "Wordpress HTML: " + html);
wb.setBackgroundColor(Color.argb(1, 0, 0, 0));
wb.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
wb.getSettings().setDefaultFontSize(WebHelper.getWebViewFontSize(this));
wb.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && (url.startsWith("http://") || url.startsWith("http://"))) {
Intent mIntent = new Intent(RssDetailActivity.this, WebviewActivity.class);
mIntent.putExtra(WebviewActivity.URL, url);
startActivity(mIntent);
return true;
} else {
Uri uri = Uri.parse(url);
Intent ViewIntent = new Intent(Intent.ACTION_VIEW, uri);
// Verify it resolves
PackageManager packageManager = getPackageManager();
List<ResolveInfo> activities = packageManager.queryIntentActivities(ViewIntent, 0);
boolean isIntentSafe = activities.size() > 0;
// Start an activity if it's safe
if (isIntentSafe) {
startActivity(ViewIntent);
}
return true;
}
}
});
if ((getResources().getString(R.string.ad_visibility).equals("0"))) {
// Look up the AdView as a resource and load a request.
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
Button btnOpen = (Button) findViewById(R.id.openbutton);
//Listening to button event
btnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(link));
startActivity(intent);
}
});
Button btnFav = (Button) findViewById(R.id.favoritebutton);
//Listening to button event
btnFav.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
mDbHelper = new FavDbAdapter(RssDetailActivity.this);
mDbHelper.open();
if (mDbHelper.checkEvent(title, description, date, link, "", "", "rss")) {
// Item is new
mDbHelper.addFavorite(title, description, date, link, "", "", "rss");
Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_success), Toast.LENGTH_LONG);
toast.show();
} else {
Toast toast = Toast.makeText(RssDetailActivity.this, getResources().getString(R.string.favorite_duplicate), Toast.LENGTH_LONG);
toast.show();
}
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.share:
String html = description;
html = html.replaceAll("<(.*?)\\>", ""); //Removes all items in brackets
html = html.replaceAll("<(.*?)\\\n", ""); //Must be undeneath
html = html.replaceFirst("(.*?)\\>", ""); //Removes any connected item to the last bracket
html = html.replaceAll(" ", "");
html = html.replaceAll("&", "");
html = html.replaceAll("‘", "‘");
String linkvalue = getResources().getString(R.string.item_share_begin);
String seenvalue = getResources().getString(R.string.item_share_middle);
String appvalue = getResources().getString(R.string.item_share_end);
String applicationName = getResources().getString(R.string.app_name);
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
//this is the text that will be shared
sendIntent.putExtra(Intent.EXTRA_TEXT, (html + linkvalue + link + seenvalue + applicationName + appvalue));
sendIntent.putExtra(Intent.EXTRA_SUBJECT, title); //you can replace title with a string of your choice
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, getResources().getString(R.string.share_header)));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.rss_detail_menu, menu);
return true;
}
}
You can send Image via Intent as ByteArray or try loading from URL. Loading from URL is preferred as it will not bring OutOfMemoryException or any other issues while passing large bitmap images via Intent. If image is small, you may pass them via Intent.
The code below shows both the methods. Implement which suits your need or works in your URL case.
Sender Activity
//Download image from thumbUrl to bitmap
URL newurl = new URL(myRssFeed.getItem(position).getThumburl());
Bitmap bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
Intent intent = new Intent(mAct, RssDetailActivity.class);
Bundle bundle = new Bundle();
bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
bundle.putString("keyDescription", myRssFeed.getItem(position).getDescription());
bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
bundle.putString("keyPubdate",myRssFeed.getItem(position).getPubdate());
//pass image url
bundle.putString("keyThumburl", myRssFeed.getItem(position).getThumburl());
//sent image bitmap byte array
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
bundle.putByteArray("byteArray", bs.toByteArray());
intent.putExtras(bundle);
startActivity(intent);
Receiver Activity
Bundle bundle = this.getIntent().getExtras();
//load from bitmap bytearray
Bitmap bitmap = BitmapFactory.decodeByteArray(bundle.getByteArray("byteArray"),0,bundle.getByteArray("byteArray").length);
imageView.setImageBitmap(bitmap);
//or load from image url
new LoadImage().execute(bundle.getString("keyThumbUrl"));
Create an AsyncTask to load image to ImageView from URL sent via Intent
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
imageView.setImageBitmap(image);
} else{
Toast.makeText(RssDetailActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).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);

How do I maintain ListView state between activity loads in android

I'm doing some background processing in my activity and have a ListView that shows the progress. I 'update' the listView with
adapter.notifyDataSetChanged();
However when I leave the activity and then come back, the background processes are still running, but the list view isn't updated. This is presumably because it's a new object, not the previous one. How do I maintain my list view object between activity loads?
This is my activity. I think the issue is that the 'adapter' variable that the download uses to bind to to show updates, is recreated in the onCreate method of the activity, and the 'adapter' variable that the download originally bound to is not in the activity anymore.
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.model.ProgressEvent;
import com.amazonaws.services.s3.model.ProgressListener;
import com.amazonaws.services.s3.transfer.TransferManager;
//import com.amazonaws.auth.AWSCredentials;
//import com.amazonaws.auth.BasicAWSCredentials;
public class VideosActivity extends Activity {
ListView video_list;
CustomList adapter;
File storage_dir;
SharedPreferences completed_downloads; //http://developer.android.com/guide/topics/data/data-storage.html
SharedPreferences downloaded_data; //maps position to percent downloaded
SharedPreferences queue; //holds which fiiles are awaiting download
String images[]; //holds references to all thumnails for vids
String volume; //something like vol1 or vol2
String s3_dir; //the directory after the boucket that the files are stored in (do not add first slash)
String s3_bucket = "com--apps";
Handler handler = new Handler(); //'tunnel' through whci other threads communicate with main thread
Map<String, String[][]> video_config = new HashMap<String, String[][]>(); //holds info about video thumbs and filenames for all apps
ArrayList<String> arr_videos = new ArrayList<String>(); //holds video names
DownloadQueue queue_manager = new DownloadQueue();
#Override
public void onCreate(Bundle savedInstanceState) {
Log.v("dev", "onCreateCalled");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
volume = getPackageName().split("\\.")[2]; //something like vol1 or vol2
s3_dir = "android/" + volume + "/"; //the directory after the boucket that the files are stored in (do not add first slash)
completed_downloads = getSharedPreferences("completed_downloads", 0);
downloaded_data = getSharedPreferences("downloaded_data", 0);
queue = getSharedPreferences("queue", 0);
storage_dir = getApplicationContext().getExternalFilesDir(null); //private to app, removed with uninstall
adapter = new CustomList(this, R.layout.customlist, arr_videos);
video_list = (ListView)findViewById(R.id.list);
video_list.setAdapter(adapter); //set adapter that specifies list contents
ensureStorageDirExists( storage_dir ); //make sure storage dir exists
set_video_data(); //store vid dat in array
ensure_connection_or_warn();
}
public boolean ensure_connection_or_warn()
{
if(have_connection())
{
return true;
}
else
{
Toast.makeText(this, "No Internet connection", Toast.LENGTH_LONG).show();
return false;
}
}
protected void ensureStorageDirExists( File dir )
{
if (!dir.exists())
{
dir.mkdirs();
}
}
public void set_video_data()
{
config_video_data(); //run config
images = video_config.get(getPackageName())[0]; //set images
for (String name : video_config.get(getPackageName())[1] ) { //set video info, this should be streamlined but is due to legacy code and my crap Java skills, consider doing like this: http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray
arr_videos.add(name);
}
}
public SharedPreferences stored_vals()
{
return PreferenceManager.getDefaultSharedPreferences(this);
}
public boolean have_connection()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo()!=null && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isAvailable())
{
Log.v("dev", "have internet connection");
return true;
}
else
{
Log.v("dev", "No internet connection");
return false;
}
}
public class DownloadQueue
{
protected void process()
{
if (queue.size() > 0 && queue.get(0).download_status == "queued") //this is meant to force one download at a time
{
queue.get(0).start();
adapter.notifyDataSetChanged();
}
}
protected void add(Integer position)
{
queue.edit.putInt(position+"");
d.download_status = "queued";
adapter.notifyDataSetChanged();
}
protected boolean position_is_queued(Integer position)
{
for (Download d : queue ) {
if(d.position == position)
{
return true;
}
}
return false;
}
protected void remove(Download d)
{
queue.remove(d);
adapter.notifyDataSetChanged();
}
}
public class CustomList extends ArrayAdapter<String>
{
View view;
int position;
Button btn;
public CustomList(Context context, int layout_id, ArrayList<String> objects)
{
super(context, layout_id, objects);
}
#Override
public View getView(final int position, View convertView, ViewGroup view_group)
{
set_view(convertView);
this.position = position;
TextView text_view = (TextView) view.findViewById(R.id.name);
ImageView image = (ImageView) view.findViewById(R.id.img);
btn = (Button) view.findViewById(R.id.play);
prepare_btn();
text_view.setText( list_text() );
image.setImageResource(
getResources().getIdentifier(images[position], "drawable", getPackageName())
);
return view;
}
public String list_text()
{
String s = arr_videos.get( position ).replace("_", " ").replace(".m4v", "");
s = s.substring(2, s.length());
return s;
}
public void set_view(View convertView)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.customlist, null);
}
else
{
view = convertView;
}
}
public Boolean is_downloaded()
{
return completed_downloads.getBoolean(position + "", false);
}
public void prepare_btn()
{
btn.setTag((Integer) position);
if(is_downloaded() == true)
{
btn.setText("Play ");
btn.setEnabled(true);
btn.setOnClickListener( new OnClickListener()
{
public void onClick(View btn)
{
int position = (Integer) btn.getTag();
Intent i = new Intent(VideosActivity.this, PlayVideoActivity.class);
String video_path = storage_dir + "/" + arr_videos.get(position);
Log.v("video_path", video_path);
i.putExtra("video_path", video_path);
startActivity(i);
}
});
}
else if( downloaded_data.contains(position+"") ) //it it's currently being downloaded
{
btn.setText(downloaded_data.getInt(position+"", 0) + "%");
btn.setEnabled(false);
}
else if( queue_manager.position_is_queued(position) ) //it's in the queue
{
btn.setText("Queued");
btn.setEnabled(false);
}
else
{
btn.setText("Download");
btn.setEnabled(true);
btn.setOnClickListener( new OnClickListener()
{
public void onClick(View btn)
{
int position = (Integer) btn.getTag();
btn.setEnabled(false);
queue_manager.add(position);
}
});
}
}
}
public class Download
{
File new_video_file;
int position;
String download_status;
com.amazonaws.services.s3.transfer.Download download;
protected void queue(int position)
{
this.position = position;
queue_manager.add(this);
queue_manager.process();
//put this download in the queue
//start downloading if it's the only one in the queue
}
protected void start()
{
if(!ensure_connection_or_warn())
{
return;
}
this.download_status = "started";
this.new_video_file = new File(storage_dir, arr_videos.get(position)); //local file to be writtent to
TransferManager tx = new TransferManager(credentials);
//http://stackoverflow.com/questions/6976317/android-http-connection-exception
this.download = tx.download(s3_bucket, s3_dir + arr_videos.get(position), new_video_file);
download.addProgressListener(new ProgressListener()
{
public void progressChanged(final ProgressEvent pe)
{
handler.post( new Runnable()
{
#Override
public void run()
{
if ( pe.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE )
{
Download.this.onComplete();
}
else
{
Download.this.onProgressUpdate();
}
}
});
}
});
}
//protected void onProgressUpdate(Double progress)
protected void onProgressUpdate()
{
this.download_status = "downloading";
Double progress = this.download.getProgress().getPercentTransfered();
Integer percent = progress.intValue();
//Log.v("runnable", percent + "");
downloaded_data.edit().putInt(position+"", percent).commit();
adapter.notifyDataSetChanged();
}
protected void onComplete()
{
Log.v("dev", "download complete!!!");
//downloaded_data.remove(position);
this.download_status = "complete";
completed_downloads.edit().putBoolean(position + "", true).commit();
queue_manager.remove(this);
queue_manager.process();
adapter.notifyDataSetChanged();
// this.download.abort();
}
}
}
Not exactly sure what happens during background processing and what do you mean by ListView state, but my suggestion would be:
try the following:
#Override
protected void onResume() {
super.onResume();
yourAdapter.clear();
yourAdapter.addAll(yourData); // API level [1..10] use for(..){ yourAdapter.add(yourData.get(index)) }
yourAdapter.notifyDataSetChanged();
}
Reason:
An adapter keeps a copy of all the elements, so when you call notifyDataSetChanged, it checks its own copy of the elements

Categories

Resources