I have a data that i need to pass as Double[],
my data is in double[], and i need to pass as Double[] because i need
to change it into List<Double>
Here is my code
ListFragment
#Override
public void OnEditItem(int position) {
Model selectedItem = mModel.get(position);
String selectedKey = selectedItem.getKey();
String selectedImage = selectedItem.getImagesUri();
String selecteDescriptions = selectedItem.getImageDescription();
String selectedImagesName = selectedItem.getImageNames();
List<Double> selectedataSet = selectedItem.getDataSet();
double[] zeroSet = new double[selectedataSet.size()];
for(int i=0; i<zeroSet.length; i++){
zeroSet[i] = selectedataSet.get(i);
}
Log.d(TAG, "thisList: " + datacel);
EditFragment editFragment = new EditFragment();
FragmentTransaction fragmentTransaction =
getActivity().getSupportFragmentManager()
.beginTransaction();
final Bundle bundle = new Bundle();
bundle.putString("Label", selectedKey);
bundle.putString("Image", selectedImage);
bundle.putString("Descriptions", selecteDescriptions);
bundle.putString("ImagesName", selectedImagesName);
And this is the code that receive the double[]
EditFragment
private void updateView(View view) {
if(getArguments()!=null){
String labelId = getArguments().getString("Label");
String imagesBundle = getArguments().getString("Image");
String descriptionsBundle =getArguments().getString("Descriptions");
String imagesNameBundle =getArguments().getString("ImagesName");
double[] dataSet = getArguments().getDoubleArray("DataSet");
//this i where i need to change into Double[];
Log.d(TAG, "thisLIst: " + dataSet);
etName.setText(String.valueOf(imagesNameBundle));
etDescribe.setText(descriptionsBundle);
Picasso.get().load(imagesBundle).into(ImageInput);
simpleActivity.setDataToListView(value, listViewDataSet,context); // this value need Double[];
Edited
i think my error starting from here,
double[] zeroSet = new
double[selectedataSet.size()];
for(int i=0; i<zeroSet.length; i++){
zeroSet[i] = selectedataSet.get(i);
}
because the data i got just like this,
how can i solve this?
It's not complicated at all. You just have to copy the array elements yourself, like
double[] dataSet = getArguments().getDoubleArray("DataSet");
Double[] boxedDataSet = new Double[dataSet.length];
for ( int i = 0; i < dataSet.length; i++ ) {
boxedDataSet[i] = dataSet[i]; // Invokes auto-boxing
// Equivalent, more explicit alternative:
// boxedDataSet[i] = Double.valueOf(dataSet[i]);
}
Try something like this:
import java.util.Arrays;
class BoxArrayExample {
public static void main(String[] args) {
double[] arr = new double[] {1.0, 2.0, 3.0};
System.out.println(String.format("Unboxed array: %s", Arrays.toString(arr)));
Double[] boxedArr = Arrays.stream(arr)
.boxed()
.toArray(Double[]::new);
System.out.println(String.format("Boxed array: %s", Arrays.toString(boxedArr)));
}
}
Output:
Unboxed array: [1.0, 2.0, 3.0]
Boxed array: [1.0, 2.0, 3.0]
Related
I was trying to make a graph based on the two array values, i.e conc and optical density. I have created two activities for saving those arrays and pass the array list using bundle and intent to the third activity using string.
Whenever I try to run the code, my app crashes.
GraphView gpView;
String co;
String od;
Float x,y;
int l1,l2;
DataPoint [] dp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
Bundle bundle1 = getIntent().getExtras();
ArrayList<String> array1 = (ArrayList<String>) bundle1.getStringArrayList("Conc");
Bundle bundle2 = getIntent().getExtras();
ArrayList<String> array2 = (ArrayList<String>) bundle2.getStringArrayList("Od");
gpView= findViewById(R.id.graph);
LineGraphSeries <DataPoint> series = new LineGraphSeries<>();
l1 = array1.size();
l2 = array2.size();
if((array1.contains(true))&&(array2.contains(true)))
{
for (int c1 = 0; c1<l1; c1++)
{
for(int c2=0; c2<l2; c2++ ) {
co = array1.get(c1);
od = array2.get(c2);
x = Float.parseFloat(co);
y = Float.parseFloat(od);
dp[c1] = new DataPoint(x,y);
}
}
gpView.addSeries(series);
}
}
Alternately I tried to run a simple input method and it worked using this
private DataPoint[] getDataPoint ()
{
dp = new DataPoint[]
{
new DataPoint(10, 0.2),
new DataPoint(20, 0.38),
new DataPoint(30, 0.45),
new DataPoint(40, 0.69),
new DataPoint(50, 0.81),
};
return (dp);
}
I think you haven't initialized your dp array. Initialize your array
dp = new DataPoint[l1];
before if statement if((array1.contains(true))&&(array2.contains(true)))
Edit:
May be you are having NullPointerException. Check array1 and array2 is not null
if(array1 == null){
Toast.makeText(this, "array1 is null", Toast.LENGTH_LONG).show();
}
if(array2 == null){
Toast.makeText(this, "array2 is null", Toast.LENGTH_LONG).show();
}
if(array1 != null){
l1 = array1.size();
}
if(array2 != null){
l2 = array2.size();
}
if(l1 > 0){
dp = new DataPoint[l1];
for (int c1 = 0; c1<l1; c1++)
{
for(int c2=0; c2<l2; c2++ ) {
co = array1.get(c1);
od = array2.get(c2);
x = Float.parseFloat(co);
y = Float.parseFloat(od);
dp[c1] = new DataPoint(x,y);
}
}
gpView.addSeries(series);
}
if array1 and array2 is null then make sure you are passing both arraylist via Intent.
I'm tried to sort the database from a web service by using the bubble sort.
itemLists[i] = new ItemList(
a.getString(id),
a.getString(nama),
a.getString(latitude),
a.getString(longitude),
a.getString(alamat));
double terendah = Double.valueOf(a.getString("TAG_TERENDAH")).doubleValue();
//double terendah = a.getDouble(terenda);
harga[i] = terendah;
//bubble sort
double tHarga;
ItemList tItemList;
for (int k = 0; k < tempatrental.length(); k++) {
for (int l = 0; l < tempatrental.length() - (k + 1); l++) {
if (harga[l] > harga[l + 1]) {
tHarga = harga[l];
tItemList = itemLists[l];
harga[l] = harga[l + 1];
itemLists[l] = itemLists[l + 1];
harga[l + 1] = tHarga;
itemLists[l + 1] = tItemList;
}
}
Anyways, database from the web service is array type, so I store it in the array from another class.
public class ItemList{
public String label1, label2, label3, label4, label5;
public ItemList(String label1, String label2, String label3, String label4, String label5) {
super();
// TODO Auto-generated constructor stub
//this.icon = icon;
this.label1 = label1;
this.label2 = label2;
this.label3 = label3;
this.label3 = label4;
this.label3 = label5;
}
The problem came when I tried to show the results of sorting in the list view.
this.setListAdapter (new ArrayAdapter<String>(TermurahActivity.this, android.R.layout.simple_list_item_1, itemLists));
Eclipse says : The Constructor ArrayAdapter(TermurahActivity, int, ItemList[]) is undefined. Please help fix to fix this...
Once you defined ArrayAdapter<String> the adapter expects a list of String.
ItemLists is a list of ItemList so you should use:
new ArrayAdapter<ItemList>(TermurahActivity.this,
android.R.layout.simple_list_item_1, itemLists);`
So, I have at this point a collections.sort of java values as you can see
and I have two keys that are integers (let's say for the sake of the example that the values of tipo are 1,2 and the values of id are 3 and 4) and I want to sort the result of theyr multiplication:
Something like this:
valA = a.get(KEY_ONE)*a.get(KEY_TWO);
valB = b.get(KEY_ONE)*b.get(KEY_TWO);
Then compare them.
How can I do it??
here is the code that I have at this point.
Collections.sort( jsonValues, new Comparator<JSONObject>() {
private static final String KEY_ONE = "tipo";
private static final String Key_TWO = "id";
#Override
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get(KEY_ONE.toString());
valB = (String) b.get(KEY_ONE.toString());
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonValues.get(i));
}
tvJson.setText(sortedJsonArray.toString());
}
}
Thanks in advance !
Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}
In my web service I'm making a query to a database, and I would like to return 2 columns of the database and put these columns in a 2d array.
Also I would like to convert the array to JSON and send it to the client. The client using gson parses the message from the server in a 2d array. Is it possible?
I have tried a lot but no luck till now. Thank you in advance.
The last version i've tried is this:
private static String[][] db_load_mes (String u){
ArrayList<String> array1 = new ArrayList<String>();
ArrayList<String> array2 = new ArrayList<String>();
JSONObject messages = new JSONObject();
Connection c = null;
try{
// Load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c = DriverManager.getConnection("jdbc:odbc:dsn1","mymsg","mymsg");
Statement s = c.createStatement();
// SQL code:
ResultSet r;
r = s.executeQuery("select * from accounts ");
int i = 0, j = 0;
int k = 0;
String x,y;
while(r.next()) {
x = r.getString("username");
array1.add(x);
y = r.getString("password");
array2.add(y);
k = k + 1;
}
int count = array1.size();
String[][] row = new String[count][2];
Iterator<String> iter = array1.iterator();
while (iter.hasNext()) {
row[i][0]=iter.next();
i++;
}
Iterator<String> iter2 = array2.iterator();
while (iter2.hasNext()) {
row[j][1]=iter2.next();
j++;
}
for(int z=0;z<count;z++)
System.out.println(row[z][0] + "\t" + row[z][1] + "\n");
if (k == 0)
System.err.println("no accounts!");
c.close();
s.close();
}
catch(SQLException se)
{
System.err.println(se);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ...;
}
With the above code I can create the 2d array but how can I send this array to the client.
Here is how I made it using Gson from google...
Download gson from here
include it in your project.
package javaapplication1;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JavaApplication1 {
public static void main(String[] args) {
int rows = 3;
String records[][] = new String[][]{{"bob", "123-pass"},
{"erika", "abc123"},
{"richard", "123123123"}
};
Gson gson = new Gson();
String recordsSerialized = gson.toJson(records);
System.out.println(recordsSerialized);
/* prints this
[["bob","123-pass"],["erika","abc123"],["richard","123123123"]]
*/
// if you want a better output import com.google.gson.GsonBuilder;
Gson gsonPretty = new GsonBuilder().setPrettyPrinting().create();
String recordsSerializedPretty = gsonPretty.toJson(records);
System.out.println(recordsSerializedPretty);
/* PRINTS IN different lines.. I can't paste it here */
// for retrieval
String retrievedArray[][] = gsonPretty.fromJson(recordsSerializedPretty, String[][].class);
for (int i = 0; i < retrievedArray.length; i++) {
for (int j = 0; j < retrievedArray[0].length; j++) {
System.out.print(retrievedArray[i][j]+" ");
}
System.out.println("");
}
// PRINTS THIS
/*
bob 123-pass
erika abc123
richard 123123123
*/
}
}