Adding a item from another activity to ExpandableListView - java

I want to add a item to the child Today from another activity to the ExpandableListView. The activity where I want to add it is named LocHistory, here is a the code to add something to the list:
static void addListData(final Context context) {
List<NewsItem> list = listDataChild.get("Today");
NewsItem newsData = new NewsItem();
newsData = new NewsItem();
newsData.setHeadline("11.11111, 1.1111");
newsData.setSpeed("1.11KM/H");
newsData.setDirection("111");
newsData.setDate("11-1-1111 11:11:11");
list.add(0, newsData);
listDataChild.put("Today", list);
}
This is working when I have call the function in the same class (LocHistory). But when I call it in MainActivity like this:
public class MainActivity extends Activity {
Button button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2 = (Button) this.findViewById(R.id.button2);
button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LocHistory.addListData(getBaseContext());
}
});
}
}
Then there is nothing added to the list. Is it possible to add a item from another activity to ExpandableListView? I want if there's something added that the class LocHistory is not going to open, so I think startActivity with a intent is not a option here (but i'm not sure).
(The java sources can be found here:
MainActivity.java,
LocHistory.java,
NewsItem.java and
ExpandableListAdapter.java)
Edit:
As some guys on a other forum pointed out, I'm now using SharedPreferences. I'm using this code:
static void addListData (int TimeStamp, final String lat, final String lng, final String speed,
final String direction, final Context context){
int todaystamp = startOf("today");
int yesterdaystamp = startOf("yesterday");
String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString();
SharedPreferences pref = context.getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
if (TimeStamp >= todaystamp) {
editor.putString("Today", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp >= yesterdaystamp) {
editor.putString("Yesterday", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
} else if (TimeStamp < yesterdaystamp) {
editor.putString("Older", "*headline=" + lat + ", " + lng + ";speed=" + speed + ";direction=" + direction + ";date=" + Datetime + ";");
}
editor.commit();
}
But now I'm stuck with one problem, when I add a item to the SharedPreferences on the same key it will overwrite the previous data. How can I add data to the same key without overwriting the previous data? Is it maybe possible to first get the data and then join the item to the data after that add the data to the SharedPreferences?

For you last edit you can try this:
static void addListData(int TimeStamp, final String lat, final String lng,
final String speed, final String direction, final Context context) {
int todaystamp = startOf("today");
int yesterdaystamp = startOf("yesterday");
String Datetime = DateFormat.format("dd-MM-yyyy kk:mm:ss", new Date(TimeStamp * 1000L)).toString();
String location = "*headline=" + lat + ", " + lng + ";speed=" + speed
+ ";direction=" + direction + ";date=" + Datetime + ";";
SharedPreferences pref = context.getSharedPreferences("myPrefs",
MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
if (TimeStamp >= todaystamp) {
String today = pref.getString("Today",null);
if (today != null) {
StringBuilder str = new StringBuilder(today);
str.insert(0, location + ", ");
editor.putString("Today", str.toString());
} else {
editor.putString("Today", location);
}
} else if (TimeStamp >= yesterdaystamp) {
String yesterday = pref.getString("Yesterday",null);
if (yesterday != null) {
StringBuilder str = new StringBuilder(yesterday);
str.insert(0, location + ", ");
editor.putString("Yesterday", str.toString());
} else {
editor.putString("Yesterday", location);
}
} else if (TimeStamp < yesterdaystamp) {
String older = pref.getString("Older",null);
if (older != null) {
StringBuilder str = new StringBuilder(older);
str.insert(0, location + ", ");
editor.putString("Older", str.toString());
} else {
editor.putString("Older", location);
}
}
editor.commit();
}
This will ensure that it not overrides the key but append if it exists. (This is done by checking whether the SharedPreferences is not null for a specific key).
I use StringBuilder with the insert method in this case.

Related

I want to merge the total price and quantity of the item in cart which is selected multiple times from movies list instead of same listings multiple

The problem lies in section where i am getting and sending results. some problem with the logic is there because the items of same kind are listed multiple times instead of updating existing row
when i add same item again it generates another row and post it there instead of updating existing same item row
public class MainActivity extends AppCompatActivity
{ ArrayList<cinema> cinemaArrayList=new ArrayList<cinema>();
ListView listView;
TextView total1;
int total12;
String quantity="";
int id;
ArrayList<String> cartItems = new ArrayList<String>();
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onActivityResult(ActivityResult result) {
Intent data = result.getData();
if (result.getResultCode() == RESULT_OK && data != null) {
id = data.getIntExtra("id", 0);
total12 += data.getIntExtra("total", 0);
total1.setText("Total: " + total12 + "$");
String name = data.getStringExtra("name");
String price = data.getStringExtra("price");
quantity = data.getStringExtra("quantity");
int j=0;
if (cartItems.size() > 0) {
for (int i = 0; i<cartItems.size(); ) {
String[] info = cartItems.get(i).toString().split(",");
String name1 = info[0];
String quantity1 = info[1];
String price1 = info[2];
String id1 = info[3];
if (id == Integer.parseInt(id1)) {
j = Integer.parseInt(quantity1) + Integer.parseInt(quantity);
String item = name1 + "," + j + "," + price1 + "," + (Integer.parseInt(price) * j+","+id1 );
cartItems.set(i, item);
break;
} else {
i++;
}
}
}
if(j==0){
String item = name + "," + quantity + "," + price + "," + (Integer.parseInt(price) * Integer.parseInt(quantity)) + "," + id;
cartItems.add(item);
}}
if(result.getResultCode() == RESULT_OK && data == null){
total12=0;
total1.setText("Total: 0 $");
cartItems.clear();
}
}
});

Play sequence of animations on one view from onAnimationEnd

I'm trying to play a sequence of more than 1 animations on the same progress bar. I am actually using a library called AnimateHorizontalProgressBar which allows the progress bars to fill up with an animation. The bar is an experience bar in a game, and if the player gets enough experience at one time, I want the bar to fill up as many times as there are level ups. (e.g. a level 1 character going to level 3 would have their experience bar fill up 2 full times, resetting whenever it gets full, then once more for however much progress they made from level 3 to level 4)
The solution I tried was to set an AnimateProgressListener on the AnimateHorizontalProgressBar, and in the onAnimationEnd function, to call the next animation to be played. The list containing these animations is an arraylist of custom POJOs which hold a reference to the view (the progress bar), and the percent to set it to.
public class MonsterBattleResolutionFragment extends MMOBaseFragment {
private static final String TAG = "Resolution Frag";
boolean isVictorious;
boolean playerCapturedMonster;
private String wildMonsterId;
ToolTipManager tooltips;
int monsterLevel;
private FirebaseFunctions mFunctions;
private ArrayList<String> monsterKeys;
private ArrayList<PlayerMonster> monstersList;
private BattleResolutionXpGainedAdapter battleResolutionXpGainedAdapter;
private Typeface typeface;
TextView victoryTextView;
private ListView xpGainedLayoutContainer;
private RecyclerView itemRecyclerView;
private PlayerItemAdapter playerItemAdapter;
ArrayList<PlayerItem> playerItems;
private FirebaseUser user;
private DatabaseReference mDatabase;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_monster_battle_resolution, container, false);
mFunctions = FirebaseFunctions.getInstance();
typeface = CustomTypeFace.getNovemberTypeface(getContext());
victoryTextView = view.findViewById(R.id.monster_battle_resolution_text_view);
victoryTextView.setTypeface(typeface);
tooltips = new ToolTipManager(getActivity());
itemRecyclerView = view.findViewById(R.id.monster_battle_resolution_item_recycler_view);
itemRecyclerView.setNestedScrollingEnabled(false);
itemRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
playerItems = new ArrayList<>();
playerItemAdapter = new PlayerItemAdapter(playerItems);
itemRecyclerView.setAdapter(playerItemAdapter);
isVictorious = getArguments().getBoolean("victory");
playerCapturedMonster = getArguments().getBoolean("playerCapturedMonster");
monsterLevel = getArguments().getInt("monsterLevel");
monsterKeys = getArguments().getStringArrayList("monsterKeys");
monstersList = getArguments().getParcelableArrayList("monstersList");
for (int i = 0; i < monstersList.size(); i++){
Log.e(TAG, monstersList.get(i).getMonsterStringName());
}
wildMonsterId = getArguments().getString("wildMonsterId");
ArrayList<String> playerMonsterIds = new ArrayList<>();
for (int i = 0; i < monstersList.size(); i++){
Log.e(TAG, "fb id is " + monstersList.get(i).getFirebaseId());
playerMonsterIds.add(monstersList.get(i).getFirebaseId());
}
Task<HashMap<String, Integer>> test = firebaseResolveCombat(wildMonsterId, playerMonsterIds);
test.addOnCompleteListener(new OnCompleteListener<HashMap<String, Integer>>() {
#Override
public void onComplete(#NonNull Task<HashMap<String, Integer>> task) {
Object gainedXp = task.getResult().get("experience");
Object items = task.getResult().get("items");
Object skills = task.getResult().get("skills");
Object newMonsterLevels = task.getResult().get("newMonsterLevels");
// gainedXp is the xp gained for each monster involved in the fight
if (gainedXp != null){
Log.e(TAG, "experience earned: " + gainedXp);
updateXpBars((int) gainedXp);
}
if (items != null){
Log.e(TAG, "items earned: " + items.toString());
HashMap<String, Integer> itemsEarnedMap = (HashMap<String, Integer>) items;
for (Map.Entry<String, Integer> item : itemsEarnedMap.entrySet()) {
Log.e(TAG, "key: " + item.getKey() + ", value: " + item.getValue());
// add new item to list for adapter. NOTE: as of now, key is a string, while value (quantity) is an int. slight issue on javascript side, fine for now.
playerItems.add(ItemDirectory.itemLookup(Integer.parseInt(item.getKey()), item.getValue()));
}
}
if (skills != null){
Log.e(TAG, "new skills: " + skills.toString());
HashMap<String, ArrayList<Integer>> newSkills = (HashMap<String, ArrayList<Integer>>) skills;
for (Map.Entry<String, ArrayList<Integer>> item : newSkills.entrySet()) {
for (Integer skill : item.getValue()) {
String skillName = SkillDirectory.skillLookup(skill).getName();
Log.e(TAG, item.getKey() + " learned skill " + skillName);
for (int i = 0; i < monstersList.size(); i++){
Log.e(TAG, "fb id is " + monstersList.get(i).getFirebaseId());
if (monstersList.get(i).getFirebaseId().equals(item.getKey())){
Toast.makeText(getContext(), monstersList.get(i).getMonsterStringName() + " learned skill " + skillName + "!", Toast.LENGTH_SHORT).show();
}
}
}
}
}
if (newMonsterLevels != null){
Log.e(TAG, "new levels: " + newMonsterLevels.toString());
}
}
});
xpGainedLayoutContainer = view.findViewById(R.id.monster_battle_resolution_xp_gained_layout_container);
battleResolutionXpGainedAdapter = new BattleResolutionXpGainedAdapter(getActivity(), R.layout.battle_resolution_xp_gained_layout, monstersList);
xpGainedLayoutContainer.setAdapter(battleResolutionXpGainedAdapter);
justifyListViewHeightBasedOnChildren(xpGainedLayoutContainer);
// if the player did not win, don't show items won, give them half xp
if (!isVictorious) {
victoryTextView.setText(R.string.defeat);
}
// listener for button to return to map
FloatingActionButton b = view.findViewById(R.id.monster_battle_resolution_return_to_map_button);
b.setOnClickListener(view1 -> {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
});
return view;
}
private void updateXpBars(int xpPerMonster){
ArrayList<LevelUpBarAnimation> animationList = new ArrayList<>();
// First build the list of animations
Log.e(TAG, "There are " + battleResolutionXpGainedAdapter.getCount() + " xp bars to animate");
for (int i = 0; i < battleResolutionXpGainedAdapter.getCount(); i++){
int currentXp = monstersList.get(i).getExperience();
int level = monstersList.get(i).getLevel();
int newXp = currentXp + xpPerMonster;
int lastLevelXp = getExperienceRequiredForNextLevel(level-1);
boolean isLevelUp = false;
int xpNumerator = newXp - lastLevelXp;
int xpDenominator = getExperienceRequiredForNextLevel(level) - lastLevelXp;
Log.e(TAG, "Monster was level: " + level + ", and had " + currentXp + " xp");
Log.e(TAG, "now has " + newXp + " xp. level now: " + getLevelBasedOnExperience(newXp));
// In a loop, build up every animation which needs to be done on this particular xp bar. Loop is so multiple animations may be played for multiple level ups\
// do while because even when the monster does not level up, they still will get some xp so at least 1 anim needs to be played
do {
isLevelUp = false; // Need to reset to know when we have not leveled up
AnimateHorizontalProgressBar bar = xpGainedLayoutContainer.getChildAt(i).findViewById(R.id.battle_resolution_xp_gained_xp_bar);
bar.setMax(10000);
if (newXp > getExperienceRequiredForNextLevel(level)){
isLevelUp = true;
level++;
xpNumerator = xpDenominator; // Sets the xp bar to full before resetting at 0 for the next level
}
Log.e(TAG, "Added new anim for bar at position " + i + ", " + "out of 10000: " + (int) (((double) xpNumerator / (double) xpDenominator) * 10000.0));
// TODO: clean up messy cast
LevelUpBarAnimation levelUpBarAnimation = new LevelUpBarAnimation(bar, (int) (((double) xpNumerator / (double) xpDenominator) * 10000.0), level);
levelUpBarAnimation.setLevelUp(isLevelUp);
Log.e(TAG, "islevelup set to " + String.valueOf(levelUpBarAnimation.isLevelUp()) + ", going from level " + (level-1) + " to " + (level));
levelUpBarAnimation.setLevelTxtView(xpGainedLayoutContainer.getChildAt(i).findViewById(R.id.battle_resolution_xp_gained_level_text_view));
animationList.add(levelUpBarAnimation);
} while(isLevelUp);
}
final int[] animNumber = {0};
Log.e(TAG, "animlist size " + animationList.size() + " playing across " + battleResolutionXpGainedAdapter.getCount() + " xp bars");
for (int i = 0; i < battleResolutionXpGainedAdapter.getCount(); i++) {
AnimateHorizontalProgressBar bar = animationList.get(i).getXpBar();
bar.setAnimateProgressListener(new AnimateHorizontalProgressBar.AnimateProgressListener() {
#Override
public void onAnimationStart(int progress, int max) {
Log.e(TAG, "anim #" + animNumber[0] + " starting");
}
#Override
public void onAnimationEnd(int progress, int max) {
// If this xp bar filled up, play a flash sort of animation, and update the lvl text
if (animationList.get(animNumber[0]).isLevelUp()){
int newLvl = animationList.get(animNumber[0]).getLevel();
Log.e(TAG, "level up animation playing. anim number " + animNumber[0] + ", now level " + newLvl);
// Update the lvl txt
animationList.get(animNumber[0]).getLevelTxtView().setText("LVL: " + newLvl);
// Then set the progress on this bar back to 0
animationList.get(animNumber[0]).getXpBar().setProgress(0);
}
Log.e(TAG, "anim number " + animNumber[0] + " finished, next playing " + (animNumber[0] + 1));
// Do not attempt to play the next animation if this one was the last
if (animNumber[0] < animationList.size() - 1){
animNumber[0]++;
Log.e(TAG, "playing anim number " + animNumber[0] + " to " + animationList.get(animNumber[0]).getProgressPercent() + "% full");
animationList.get(animNumber[0]).getXpBar().setProgressWithAnim(animationList.get(animNumber[0]).getProgressPercent()); // TODO: this not getting called
}
}
});
}
Log.e(TAG, "playing anim number 0");
animationList.get(0).getXpBar().setProgressWithAnim(animationList.get(0).getProgressPercent());
}
// On receiving a new skill, this tooltip will appear momentarily to notify the player
public void showNewSkillTooltip(String skillName, View view) {
Log.e(TAG, "Showing new skill tooltip. skill learned: " + skillName);
// Dynamically build a layout here, as it cannot already have a parent layout if we want to assign it to the tooltip
LinearLayout tooltipLayout = new LinearLayout(getContext());
tooltipLayout.setOrientation(LinearLayout.VERTICAL);
TextView talentTitleText = new TextView(getContext());
talentTitleText.setTextSize(18f);
talentTitleText.setText(skillName);
tooltipLayout.addView(talentTitleText);
ToolTip toolTip = new ToolTip()
.withColor(getResources().getColor(R.color.grey_300)) //or whatever you want
.withAnimationType(ToolTip.AnimationType.FROM_MASTER_VIEW)
.withContentView(tooltipLayout)
.withShadow();
tooltips.showToolTip(toolTip, view);
}
private Task<HashMap<String, Integer>> firebaseResolveCombat(String wildMonsterFirebaseId, ArrayList<String> playerMonsterIds) {
// Create the arguments to the callable function.
Map<String, Object> data = new HashMap<>();
data.put("wildMonsterId", wildMonsterFirebaseId);
data.put("playerMonsterIds", playerMonsterIds);
return mFunctions
.getHttpsCallable("resolveWildMonsterCombat")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, HashMap<String, Integer>>() {
#Override
public HashMap then(#NonNull Task<HttpsCallableResult> task) throws Exception {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
HashMap<String, Integer> result = (HashMap<String, Integer>) task.getResult().getData();
return result;
}
});
}
}
I added the whole class. Forgive the messy code.
The problem is that after the first animation which I start explicitly, it runs the onAnimationEnd function, and hits the line to run the next animation, but it never starts. The onAnimationStart function is never even called for the 2nd animation. Any ideas on why this might be?
I'll also add this takes place in a dialog fragment. Not sure if that is relevant however.

Sequential File Number Generation

Hi I have a tricky problem that seems simple but it has been teasing my brain ever since I started it.
My app allows the user to enter a Product Number and an image Number. The app can take more than one image of one product.
When saving the images to gallery I would like to add a sequential file number to it so that I know which images are linked to which product.
Here is the format in which the file will be saved:
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
For example,
Type No = Test1;
ImageNo = 1;
sequentialNumber = 1;
fname = Test1(1)1;
When the user saves this one, they go back to the data entry activity and If they keep the same TypeNo/ProductCode then the sequentialNo should stay the same for the next save.
If the user enters a different TypeNo/ProductNo then the sequentialNo will increment.
Here is the code I have tried so far which doesn't increment correctly when a new TypeNo is entered:
private void saveImageToExternalStorage(Bitmap bitmap_view) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/Digital_Images");
myDir.mkdirs();
String fname = TypeNo + "(" + ImageNo + ")" + sequentialNumber + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap_view.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
}
#Override
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = sharedPreferences.edit();
String lastUsedTypeNo = TypeNo;
editor.putString("TypeNo", lastUsedTypeNo);
editor.putInt("sequentialNum", sequentialNumber);
editor.apply();
}
#Override
public void onResume() {
super.onResume();
String TypeNoRetrieved = sharedPreferences.getString("TypeNo", null);
int SQNumRetrieved = sharedPreferences.getInt("sequentialNum", 1);
if (TypeNoRetrieved != null || SQNumRetrieved != 0) {
if (TypeNoRetrieved == lastUsedTypeNo ) {
sequentialNumber = SQNumRetrieved;
} else {
sequentialNumber++;
}
}
}
Anyone able to solve this puzzle for me?

Compare String with Bubble Sort Algorithm

I have a program that will fetch several String from database (announcementId, and announcementTitle),
then for every string fetched from the database, I want to compare each of them (Compare all the fetched announcementId),
if the string (announcementId) has different value then it will create a new Button using the announcementTitle as it's(the button) value fetch from database.
I tried to learn how, and found out that bubble sort algorithm can be used in this case, but there is some error in the program.. Index out of bound exception..
Then I tried some code and tried to change the array, but it still didnt work.
Could you please take a look at my code and tell me where is the error and the best way to fix the error
This is my code :
myDb = new Database(ViewAllAnnouncement.this);
myDb.open();
totalAnnouncement = myDb.countHowManyAnnouncement(username);
String temp = Integer.toString(totalAnnouncement);
//Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
String[] announcementTitle = myDb.fetchMyAnnouncement(username);
String[] announcementId = myDb.fetchAnnouncementId(username);
for (int i = 0; i < totalAnnouncement; i++) {
for (int j = 0; j < totalAnnouncement - i; j++) {
if (j > 0 || j < totalAnnouncement-i) {
if (!announcementId[j].equals(announcementId[i])) {
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
}
}
}
}
myDb.close();
And this is my method to return the announcementId
public String[] fetchAnnouncementId(String Username) {
// TODO Auto-generated method stub
int i = 0;
String Query = "SELECT b." + ANNOUNCEMENT_ID + " FROM "
+ MS_GROUP_DETAIL + " a, " + MS_ANNOUNCEMENT_DETAIL + " b, "
+ MS_ANNOUNCEMENT + " c WHERE a." + GROUP_ID + " = b."
+ GROUP_ID + " AND b. " + ANNOUNCEMENT_ID + " = c."
+ ANNOUNCEMENT_ID + " AND a." + MEMBER_USERNAME + " =? ORDER BY b." +ANNOUNCEMENT_ID;
Cursor c = ourDatabase.rawQuery(Query, new String[] { Username });
String temp[] = new String[c.getCount()];
int iArray = c.getColumnIndex(ANNOUNCEMENT_ID);
c.moveToFirst();
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
temp[i] = c.getString(iArray);
i++;
}
c.close();
return temp;
}
If bubble sort is the answer you must have misunderstood the question. I strongly recommend you just add
ORDER BY announcementId
to the end of your query. That way the database will sort by your column for you.
Edit
You could use
ORDER BY 1
to sort by the first column (and omit the name). And, then your code should look something like
for (int i = 0; i < totalAnnouncement - 1;) {
int j = i + 1;
for (; j < totalAnnouncement; j++) {
if (!announcementId[j].equals(announcementId[i])) {
break;
}
}
// j is the first value where the announcementId changes
newBt = new Button(this);
newBt.setTag(announcementId[i]);
newBt.setText(announcementTitle[i]);
newBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Button mButt = (Button) v;
String temp = (String) mButt.getTag();
Intent intent = new Intent(
"com.example.teamizer.VIEWCHILDANNOUNCEMENT");
intent.putExtra("annId", temp);
startActivity(intent);
}
});
layout.addView(newBt);
i = j; // <-- assign j to i.
}

why i get null when intent double value

I need to intent a double value in order to insert in SQLite but when i print output it show NULL value.
This is code intent in first Activity
Intent intent = new Intent(Process.this,AddStudent.class);
intent.putExtra("Intent", result);
startActivity(intent);
and this is code get intent in another activity
String concentrate = getIntent().getStringExtra("Intent");
Here is full code.
FirstActivity;
public class Process extends Activity {
public static double a,b,r,std_err = 0.0;
public static double e;
public static int N;
#SuppressWarnings("static-access")
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_process);
double[] x = { 10,30,50,60,90,55 };
double[] y = { 1, 10, 20, 30, 40, 50 };
Process model = new Process();
model.Regression(x, y);
double result = Math.pow(2.71828182845904,x[0]*b); // e^bx
Intent intent = new Intent(Process.this,AddStudent.class);
intent.putExtra("Intent", result);
startActivity(intent);
}
//-----------------------------------------------------------------------------------//
public static void Regression (double[] oat, double[] energy) {
N = oat.length;
// constant e:
Double e = Math.E;
Double sumX = 0.00;
Double sumX2 = 0.00;
Double sumY = 0.00;
Double sumYlin = 0.00;
Double sumY2 = 0.00;
Double sumY2lin = 0.00;
Double sumXY = 0.00;
Double sumXYlin = 0.00;
for(int i=0;i<N;i++)
{
sumX = sumX + oat[i];
sumX2 = sumX2 + Math.pow(oat[i], 2);
// exponential
sumY = sumY + Math.log(energy[i]);
sumY2 = sumY2 + Math.pow(Math.log(energy[i]), 2);
sumXY = sumXY + (oat[i]*(Math.log(energy[i])));
}
b = ((N*sumXY) - (sumX*sumY))/(N*sumX2 - (sumX*sumX));
a = Math.pow(e, (sumY - (b*sumX))/N);
Double c = 0.00; // numerator
Double d = 0.00; // denominator
c = (b)*(sumXY - sumX*sumY/N);
d = sumY2 - (sumY*sumY)/N;
r = c/d;
Double p = 0.00;
if(r > 0){
p = Math.sqrt(r);
} else {
p = 0.00;
}
std_err = Math.sqrt((d-c)/(N-2));
}
}
SecondActivity; the activity for add data in SQLite
public class AddStudent extends Activity {
DatabaseStudent mHelper;
SQLiteDatabase mDb;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add);
mHelper = new DatabaseStudent(this);
mDb = mHelper.getWritableDatabase();
final EditText editName = (EditText)findViewById(R.id.editName);
final EditText editLastName = (EditText)findViewById(R.id.editLastName);
final EditText editSchool = (EditText)findViewById(R.id.editSchool);
Button buttonAdd = (Button)findViewById(R.id.buttonAdd);
buttonAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String name = editName.getText().toString();
String lastname = editLastName.getText().toString();
String school = editSchool.getText().toString();
//concentrate
//String concentrate = getIntent().getStringExtra("Intent");
String concentrate = getIntent().getStringExtra("Intent");
//Date&Time
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
if(name.length() != 0 && lastname.length() != 0
&& school.length() != 0 ) {
Cursor mCursor = mDb.rawQuery("SELECT * FROM "
+ DatabaseStudent.TABLE_NAME + " WHERE "
+ DatabaseStudent.COL_NAME + "='" + name + "'"
+ " AND " + DatabaseStudent.COL_LASTNAME + "='"
+ concentrate + "'" + " AND "
+ DatabaseStudent.COL_SCHOOL + "='" + currentTime //add COL_SCHOOL = currentTime
+ "'", null);
if(mCursor.getCount() == 0) {
mDb.execSQL("INSERT INTO " + DatabaseStudent.TABLE_NAME
+ " (" + DatabaseStudent.COL_NAME
+ ", " + DatabaseStudent.COL_LASTNAME
+ ", " + DatabaseStudent.COL_SCHOOL
+ ") VALUES ('" + name + "', '" + concentrate //result ไม่มา
+ "', '" + currentTime + "');");
editName.setText("");
editLastName.setText("");
editSchool.setText("");
}
});
}
public void onStop() {
super.onStop();
mHelper.close();
mDb.close();
}
}
You have
double result = Math.pow(2.71828182845904,x[0]*b);
and
intent.putExtra("Intent", result);
result is a double.
But when you retrieve you have
String concentrate = getIntent().getStringExtra("Intent");
Instead you should use
double concentrate = getIntent().getDoubleExtra("Intent", 0);
Reference :
http://developer.android.com/reference/android/content/Intent.html#getDoubleExtra(java.lang.String, double)
You're not actually placing your double value into your Intent. You need to use putDouble and getDouble methods.
Intent intent = new Intent(Process.this,AddStudent.class);
Bundle b = new Bundle();
b.putDouble("Intent", result);
intent.putExtras(b);
startActivity(intent);
Then, get it in your next Activity:
Bundle b = getIntent().getExtras();
double result = b.getDouble("Intent");
String concentrate = getIntent().getStringExtra("Intent");
Should be like this:
double concentrate = getIntent().getExtras().getDouble("Intent");
Wrap the passed bundle directly into double.
You are passing a Double value and trying to get a String value so you are getting null
Replace
getIntent().getStringExtra("Intent");
with
getIntent().getDoubleExtra("Intent", 0);
Try putting your double into a bundle, then passing like so
Intent intent = new Intent(Process.this,AddStudent.class);
Bundle extras = new Bundle();
intent.putExtras(b);
startActivity(intent);
Then, in your new activity
Bundle extras = Intent.getExtras();
Double result = extras.getDouble("Intent");

Categories