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");
Related
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();
}
}
});
I am very new in Android studio and Java, I tried to convert a variable sensor0 to double by using CO = new Double(sensor0).doubleValue(); , and I would like to pass the variable to another class to use it. But I cannot use the variable of sensor0 in another class. The value of the variable is always 0.
public class bt extends Activity {
public String sensor0, sensor1;
public double CO;
Button btnOn, btnOff, btnNext;
TextView txtArduino, txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID ID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bt);
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
btnNext = (Button) findViewById(R.id.buttonNext);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
sensor0 = recDataString.substring(1, 4); //get sensor value from string between indices 1-5
sensor1 = recDataString.substring(5, 8); //same again...
//String sensor2 = recDataString.substring(11, 15);
//String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" CO2 Value = " + sensor0 + ""); //update the textviews with sensor values
sensorView1.setText(" CO Value = " + sensor1 + "");
// sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
// sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
CO = new Double(sensor0).doubleValue();
}
}
}
};
you need to allow access to this variable.
the bast way to do this is to define a getter for this variable.
create a variable in the class and once your method runs populate the field
create a "public" method called getC0() which will return your value.
in the class you need this after you create an instance of your class and the logic that populates the variable runs, you can call the method to get the value.
I changed CO = new Double(sensor0).doubleValue(); to double CO = Double.parseDouble(sensor0);. Then I get 0 from another class by using the code
bt SensorCO = new bt();
double COValue = SensorCO.CO;,
and below is the code of another class
public void setBitmap( Bitmap bitmap ) {
oldTime = (System.currentTimeMillis()+500)/1000;
mBitmap = bitmap;
if (!detector.isOperational()) {
//Handle contingency
} else {
//Log.d("time1", SystemClock.currentThreadTimeMillis()+"");
Frame frame = new Frame.Builder().setBitmap(bitmap).build();
mFaces = detector.detect(frame);
}
bt SensorCO = new bt();
double COValue = SensorCO.CO;
newTime = (System.currentTimeMillis()+500)/1000;
timeDifference = (newTime - oldTime);
accumulate = (accumulate + timeDifference);
CameraActivity.showScore(blinkCount, accumulate, COValue);
if(isEyeBlinked()){
accumulate = 0;
Log.d("isEyeBlinked","eye blink is observed");
blinkCount++;
}
if(accumulate > 6){
playSound playSound1 = new playSound();
playSound1.play(accumulate);
}
invalidate();
}
make sure that sensor0 have the right value and then
replace
CO = new Double(sensor0).doubleValue();
with
double CO = Double.parseDouble(sensor0);
This is supposed to basically make the user's variables continue to increment whilist offline. $money is working fine, but it's not adding anything to $employeeupgrade1level or $employerupgrade1level and I've been trying to figure out why for hours. I'm not sure whether I'm simply overlooking something or the problem is more than that, but the the full source code's here: http://125.63.48.169/other%20stuff/business%20builder/code.txt
Posting whole script because it's probably full of things I'm overlooking, and it'd be too much to put here.
public void timer() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
$money = $money + $employeeupgrade1earnings;
$employercounter = (600 / $employerupgrade1level)*18;
$managercounter = (600 / $managerupgrade1level)*18;
if ($employerupgrade1level >= 1) {
$employeeupgrade1level = $employeeupgrade1level + (1 / $employercounter);
$employeeupgrade1earnings = $employeeupgrade1level / 10;
}
if ($managerupgrade1level >= 1) {
$employerupgrade1level = $employerupgrade1level + (1 / $managercounter);
$employerupgrade1earnings = $employerupgrade1level;
}
if ($cantafford == 1) {
Toast.makeText(getApplicationContext(), ("Can't afford this! You only have " + df.format($money) + " BB!"), Toast.LENGTH_SHORT).show();
$cantafford = 0;
}
if ($isonmainpage == 0) {
TextView cost = (TextView) findViewById(R.id.employeeupgradecost);
TextView amount = (TextView) findViewById(R.id.employeeupgradeamount);
TextView earnings = (TextView) findViewById(R.id.employeeupgradeearnings);
earnings.setText("You earn " + df.format($employeeupgrade1earnings) + " BBs every second.");
cost.setText("Costs " + df.format($employeeupgrade1cost) + " Business Bucks.");
amount.setText("You have " + noDecimals.format($employeeupgrade1level) + " casual workers.");
TextView cost2 = (TextView) findViewById(R.id.employerupgradecost);
TextView amount2 = (TextView) findViewById(R.id.employerupgradeamount);
TextView earnings2 = (TextView) findViewById(R.id.employerupgradeearnings);
earnings2.setText("You earn "+$employerupgrade1level+" casual worker(s) every 3 hours.");
cost2.setText("Costs " + df.format($employerupgrade1cost) + " Business Bucks.");
amount2.setText("You have " + noDecimals.format($employerupgrade1level) + " casual employers.");
}
updatemoney();
timer();
}
}, 1000);
}
public void offlineEarnings() {
SharedPreferences sharedpreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
lastTime = sharedpreferences.getString("currentTime", currentTime);
currentTime = String.valueOf(System.currentTimeMillis());
timeDifference = (Double.valueOf(currentTime)) - Double.valueOf(lastTime);
timeDifferenceMinutes = (timeDifference / 1000) / 60;
timeDifferenceSeconds = Double.valueOf(timeDifference) / 1000;
$offlineMoneyEarned = ($employeeupgrade1level / 10) * timeDifferenceSeconds;
$money = $money + $offlineMoneyEarned;
$managercounter = (600 / $managerupgrade1level)*18;
$employercounter = (600 / $employerupgrade1level) * 18;
if ($employercounter > 0) {
Double $offlineEmployeesEarned = Double.valueOf(Math.round(timeDifferenceSeconds / $employercounter));
$employeeupgrade1level = $offlineEmployeesEarned + $employeeupgrade1level;
} else $offlineEmployeesEarned = 0;
if ($managercounter > 0) {
Double $offlineEmployeesEarned = Double.valueOf(Math.round(timeDifferenceSeconds / $managercounter));
$managerupgrade1level = $offlineEmployeesEarned + $managerupgrade1level;
} else $offlineEmployersEarned = 0;
drawEarnings();
}
public void drawEarnings(){
if (debugmode == 1) {
SimpleDateFormat DateFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
//get string
String timeSinceLastPlayed = "Time since you last played: " + noDecimals.format(timeDifferenceSeconds) +" seconds ("+ df.format((timeDifferenceSeconds/60)) + " minutes or " + df.format(((timeDifferenceSeconds / 60)/60)) + " hours.)";
String dateLastPlayed = "Date of last session: " + DateFormatter.format(new Date(Long.valueOf(lastTime)));
String offlineMoneyEarned = "Money earned since last session: " + df.format($offlineMoneyEarned) + ".";
String offlineEmployeesEarned = "Employees earned since last session: " + $offlineEmployeesEarned + ". ";
String offlineEmployersEarned = "Employers earned since last session: " + $offlineEmployersEarned + ". ";
//get textview
TextView tvTimeSinceLastPlayed = (TextView) findViewById(R.id.timeSinceLastPlayed);
TextView tvDateLastPlayed = (TextView) findViewById(R.id.dateLastPlayed);
TextView tvOfflineMoneyEarned = (TextView) findViewById(R.id.offlineMoneyEarned);
TextView tvOfflineEmployeesEarned = (TextView) findViewById(R.id.offlineEmployeesEarned);
TextView tvOfflineEmployersEarned = (TextView) findViewById(R.id.offlineEmployersEarned);
//set text string
tvTimeSinceLastPlayed.setText(timeSinceLastPlayed);
tvDateLastPlayed.setText(dateLastPlayed);
tvOfflineEmployeesEarned.setText(offlineEmployeesEarned);
tvOfflineMoneyEarned.setText(offlineMoneyEarned);
tvOfflineEmployersEarned.setText(offlineEmployersEarned);
//make text visible
tvOfflineEmployeesEarned.setVisibility(View.VISIBLE);
tvOfflineMoneyEarned.setVisibility(View.VISIBLE);
tvDateLastPlayed.setVisibility(View.VISIBLE);
tvTimeSinceLastPlayed.setVisibility(View.VISIBLE);
tvOfflineEmployersEarned.setVisibility(View.VISIBLE);
}
}
public void buyEmployeeUpgrade1(View view) {
if ($money >= $employeeupgrade1cost) {
$money = $money - $employeeupgrade1cost;
$employeeupgrade1level = $employeeupgrade1level + 1;
$employeeupgrade1earnings = $employeeupgrade1level / 10;
$allupgrades = $employeeupgrade1earnings + $allupgrades;
double $randomCost = 1.05 + (1.4 - 1.05) * random.nextDouble();
$employeeupgrade1cost = $employeeupgrade1cost * $randomCost;
//employee upgrade
TextView cost = (TextView) findViewById(R.id.employeeupgradecost);
TextView amount = (TextView) findViewById(R.id.employeeupgradeamount);
TextView earnings = (TextView) findViewById(R.id.employeeupgradeearnings);
earnings.setText("You earn " + noDecimals.format($employeeupgrade1earnings) + " BBs every second.");
cost.setText("Costs " + df.format($employeeupgrade1cost) +" Business Bucks.");
amount.setText("You have " + noDecimals.format($employeeupgrade1level) + " casual workers.");
}
else $cantafford = 1;
}
public void buyEmployerUpgrade1(View view) {
if ($money >= $employerupgrade1cost) {
$money = $money - $employerupgrade1cost;
$employerupgrade1level = $employerupgrade1level + 1;
double $randomCost = 1.05 + (1.4 - 1.05) * random.nextDouble();
$employerupgrade1cost = $employerupgrade1cost * $randomCost;
$employercounter = (600 / $employerupgrade1level) * 18;
$employerupgrade1earnings = $employerupgrade1level;
TextView cost = (TextView) findViewById(R.id.employerupgradecost);
TextView amount = (TextView) findViewById(R.id.employerupgradeamount);
TextView earnings = (TextView) findViewById(R.id.employerupgradeearnings);
earnings.setText("You earn "+$employerupgrade1level+" casual worker(s) every 3 hours.");
cost.setText("Costs " + df.format($employerupgrade1cost) + " Business Bucks.");
amount.setText("You have " + noDecimals.format($employerupgrade1level) + " casual employers.");
} else $cantafford = 1;
}
public void buyManagerUpgrade1(View view) {
if ($money >= $managerupgrade1cost) {
$money = $money - $managerupgrade1cost;
$managerupgrade1level = $managerupgrade1level + 1;
double $randomCost = 1.05 + (1.4 - 1.05) * random.nextDouble();
$managerupgrade1cost = $managerupgrade1cost * $randomCost;
$managercounter = (600 / $managerupgrade1level) * 18;
$managerupgrade1earnings = $managerupgrade1level;
TextView cost = (TextView) findViewById(R.id.managerupgradecost);
TextView amount = (TextView) findViewById(R.id.managerupgradeamount);
TextView earnings = (TextView) findViewById(R.id.managerupgradeearnings);
earnings.setText("You earn "+noDecimals.format($managerupgrade1level)+"casual employer(s) every 3 hours.");
cost.setText("Costs " + df.format($managerupgrade1cost) + " Business Bucks.");
amount.setText("You have " + noDecimals.format($managerupgrade1level) + " casual managers.");
} else $cantafford = 1;
}
So I've fixed it. New offlineEarnings() code is this;
public void offlineEarnings() {
SharedPreferences sharedpreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
lastTime = sharedpreferences.getString("currentTime", currentTime);
currentTime = String.valueOf(System.currentTimeMillis());
timeDifference = (Double.valueOf(currentTime)) - Double.valueOf(lastTime);
timeDifferenceMinutes = (timeDifference / 1000) / 60;
timeDifferenceSeconds = Double.valueOf(timeDifference) / 1000;
$offlineMoneyEarned = ($employeeupgrade1level / 10) * timeDifferenceSeconds;
$money = $money + $offlineMoneyEarned;
if ($employerupgrade1level > 0) {
$offlineEmployeesEarned = (Double.valueOf(Math.round(timeDifferenceSeconds) / $employercounter));
$employeeupgrade1level = $offlineEmployeesEarned + $employeeupgrade1level;
} else $offlineEmployeesEarned = 0;
if ($managerupgrade1level > 0) {
$offlineEmployersEarned = (Double.valueOf(Math.round(timeDifferenceSeconds) / $managercounter));
$employerupgrade1level = $offlineEmployeesEarned + $employerupgrade1level;
} else $offlineEmployersEarned = 0;
drawEarnings();
}
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.
}
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.