I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...
In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.
Thanks for helping
Also some of my code is like this:
private void modalShowEbat() {
dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());
final CharSequence items[] = new CharSequence[list.size()];
for (int i = 0; i < list.size(); i++) {
items[i] = list.get(i).getColumnEbat();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Segment seçiniz");
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
editTextEbat.setText(items[which].toString());
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog = builder.create();
alertDialog.show();
}
This is my image of result
Use this -
segmentDao.queryBuilder().distinct().where().eq("name", "value").query();
Hi I solved my problem with below code. Maybe you can say this is long way for this. I wrote my code like below because i couldn't do other ways(using .distinct() method in ORMLite or other ORMLite's method)
If you have any other ways to solve this, i am waiting your suggestions. Thanks for everybody, happy coding...
private void modalShowEbat() {
dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());
GenericRawResults<String[]> rawResults = segmentDao.queryRaw("SELECT DISTINCT Ebat FROM Segment WHERE Segment = ? ", editTextSegment.getText().toString().trim());
final CharSequence items[] = new CharSequence[list.size()];
int i = 0;
for (String[] resultColumns : rawResults) {
String author = resultColumns[0];
items[i] = author;
i++;
}
int newLenght = 0;
for (int j = 0; j < items.length; j++) {
if (items[j] != null) {
newLenght++;
}
}
final CharSequence newItems[] = new CharSequence[newLenght];
for (int j = 0; j < newLenght; j++) {
if (items[j] != null) {
newItems[j] = items[j];
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Segment");
builder.setSingleChoiceItems(newItems, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
editTextEbat.setText(newItems[which].toString());
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog = builder.create();
alertDialog.show();
}
Related
This is my code for a button. Whenever i click this the app shuts down!I am unable to understand why it's happening?
In my code, I am trying to check if values from dynamically created EditText field has been stored on my variable array values[] and bValues[];
I looked for many answers here on how to retrieve value from dynamic edittext fields. And I came up with this from my understanding.
Can anyone tell me where am I going wrong? And a corrected demo code will be of help!
public class MainActivity extends AppCompatActivity {
private static int a;
private static EditText ainput;
private static Button btn, set;
TextView equal_sign;
private static TableLayout tableLayout;
private static LinearLayout bMatrix;
List<EditText> allEds = new ArrayList<EditText>(a*a);
double[] values = new double[(allEds.size())];
List<EditText> bMatrixValues = new ArrayList<EditText>(a);
double[] bValues = new double[bMatrixValues.size()];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ainput = (EditText) findViewById(R.id.a);
btn = (Button) findViewById(R.id.btn);
set = (Button)findViewById(R.id.set);
tableLayout = (TableLayout) findViewById(R.id.table1);
equal_sign = (TextView) findViewById(R.id.equal_sign);
bMatrix = (LinearLayout) findViewById(R.id.bMatrix);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a = Integer.parseInt(ainput.getText().toString());
tableLayout.removeAllViews();
createMatrix();
}
});
set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < allEds.size(); i++){
values[i] = Double.parseDouble(allEds.get(i).getText().toString());
}
for (int j = 0 ; j < bMatrixValues.size(); j++){
bValues[j] = Double.parseDouble(bMatrixValues.get(j).getText().toString());
}
if (allEds.size() > 0 && bMatrixValues.size() > 0){
Toast.makeText(MainActivity.this, "Main Matrix Values inserted!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this, "Insertion failed!", Toast.LENGTH_SHORT).show();
}
}
});
}
private void createMatrix() {
int p = 1;
for (int i = 0; i < a; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams lp = new
TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
row.setLayoutParams(lp);
EditText magicField;
for (int j = 0; j < a; j++) {
magicField = new EditText(MainActivity.this);
allEds.add(magicField);
magicField.setId((p));
magicField.setHint("et-" + (Integer.toString(p)));
magicField.setGravity(Gravity.CENTER);
magicField.setWidth(100);
row.addView(magicField, j);
p++;
}
tableLayout.addView(row, i);
}
bMatrix.removeAllViews();
equal_sign.setText("=");
equal_sign.setTextSize(30);
createBMatrix();
}
private void createBMatrix() {
int id = (a * a) + 1;
for (int s = 0; s < a; s++) {
final EditText b = new EditText(this);
bMatrixValues.add(b);
b.setId(id);
b.setHint("b-" + (Integer.toString(s + 1)));
b.setGravity(Gravity.CENTER);
b.setWidth(100);
bMatrix.addView(b);
id++;
}
}
}
And this is the output screen!
Matrix style edit text field gets created nicely. But when i give values to those fields and click on set value button app shuts down..
Please help. I want to display the correct answers in an alert dialog, if i type "rightAnswers" inside "builder.setMessage("Answer : " + rightAnswers);" an alert show "Answer: 1". Number 1 instead of the correct answer. please teach me what to put to be able to display the correct answer. thank you so much.
public class thisactivity extends AppCompatActivity {
Button choice1,choice2;
ImageView images;
List<Model> list;
int turn = 1;
int rightAnswers = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thisactivity);
images = (ImageView) findViewById(R.id.images);
choice1 = (Button) findViewById(R.id.choice1);
choice2 = (Button) findViewById(R.id.choice2);
list = new ArrayList<>();
for (int i = 0; i < new Signsdatabase().answers.length; i++) {
list.add(new Model(new Signsdatabase().answers[i], new
Signsdatabase().signs[i]));
}
newQuestion(turn);
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String alertTitle;
if(choice1.getText().toString().equalsIgnoreCase(list.get(turn -
1).getName())) {
rightAnswers = rightAnswers + 1;
alertTitle = "Correct!";
if (turn < list.size()) {
turn++;
newQuestion(turn);
} else {
Toast.makeText(thisactivity.this, "You have completed the Quiz!", Toast.LENGTH_SHORT).show();
}
}
AlertDialog.Builder builder = new
AlertDialog.Builder(thisactivity.this)
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + **CORRECT ANSWERS**); <---I WANT TO DISPLAY THE CORRECT ANSWER HERE BUT I DO NOT KNOW HOW------->
builder.setIcon(R.drawable.pic);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
}
});
}
});
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (choice2.getText().toString().equalsIgnoreCase(list.get(turn - 1).getName())) {
rightAnswers = rightAnswers + 1;
if (turn < list.size()) {
turn++;
newQuestion(turn);
} else {
Toast.makeText(thisactivity.this, "You have completed the Quiz!", Toast.LENGTH_SHORT).show();
getResults();
}
} else {
}
AlertDialog.Builder builder = new
AlertDialog.Builder(Roadsigns.this)
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + **CORRECT ANSWERS**); <---I WANT TO DISPLAY THE CORRECT ANSWER HERE BUT I DO NOT KNOW HOW------->
builder.setIcon(R.drawable.pic);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
}
});
builder.setCancelable(false);
builder.show();
}
});
}
............
And this is my Signsdatabase
public class Signsdatabase {
Integer[] signs ={
R.drawable.q1,
R.drawable.q2,
R.drawable.q3,
};
String[] answers = {
"Ans1",
"Ans2",
"Ans3",
};
}
Make this change in alter dialog.
make Signsdatabase object or make static in answer array.
builder.setMessage("Answer : " + Signsdatabase.answers[rightAnswers]);
You display the index of the right answer, you need to get the item from the list at the corresponding position:
builder.setMessage("Answer : " + signsdatabase.answers[rightAnswers]);
builder.setMessage("Answer : " + list[rightAnswers]);// it also check.
And you also need to initialize signsdatabase before
signsdatabase = new Signsdatabase();
Suppose you have the correct index of the answer You can do one of the following :
One
Create an object of SignsDatabase :
signsDb = new Signsdatabase();
With index i of correct answer :
builder.setMessage("Answer : "+ signDb.answers[i];
Two
If you do not want to create an instance of SignDatabase, you can declare the answers as static variable so :
public class SignDatabase{
... //some code here
public static String[] answers = ["Abc","xyz"];
}
Then access it directly by calling :
builder.setMessage(SignDatabase.answers[i]);
Actually I have one filtered array. I want to store that ArrayList in another ArrayList, but it is not adding. I am saving one model to another. because I want only that filteredlist.
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ComboViewHolder> {
private ArrayList<Products> catList;
private ArrayList<FilteredCategorymodel> filterList;
Context context;
int count = 0;
// ArrayList<FilteredCategorymodel> filterModel;
SharedPrefrences sharedPrefrences;
boolean isClicked = true;
public ProductAdapter(Context context, ArrayList<Products> catList) {
this.catList = catList;
this.context = context;
}
#Override
public ComboViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.combo_list_item, parent, false);
return new ComboViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ComboViewHolder holder, final int position) {
final Products products = catList.get(position);
Log.e("Products Items::::", products + "");
holder.mProductName.setText(products.getProduct_name());
holder.mProductDescription.setText(products.getProduct_description());
holder.mDescription.setText(products.getRecipe_method());
holder.mPrice.setText(products.getPrice());
Picasso.with(context)
.load(Constants.Image_Path + products.getProduct_image())
.placeholder(R.drawable.common_signin_btn_icon_focus_light) // optional
.error(R.drawable.common_signin_btn_icon_dark) // optional
.into(holder.mPImage);
holder.mPImage.setTag(holder);
holder.btnIncrese.setTag(position);
holder.btnDecrese.setTag(position);
holder.btnIncrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mPosition = (int) v.getTag();
Log.e("mPosition~", mPosition + "~" + position);
count = catList.get(mPosition).getCount() + 1;
for (int i = 0; i < catList.size(); i++) {
filterList = new ArrayList<FilteredCategorymodel>();
filterList.add(catList.get(i));
}
basketCount = basketCount + 1;
catList.get(mPosition).setCount(count);
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
}
});
holder.btnDecrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// int position = (Integer) v.getTag();
int mPosition = (int) v.getTag();
if (catList.get(mPosition).getCount() < 1) {
holder.mQuantity.setText("0");
} else {
count = catList.get(mPosition).getCount() - 1;
basketCount = basketCount - 1;
catList.get(position).setCount(count);
Log.e("COUNT::::", count + "");
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
// sharedPrefrences = new SharedPrefrences();
// sharedPrefrences.addFavorite(context, catList.get(mPosition));
// Toast.makeText(context, "Fave",
// Toast.LENGTH_SHORT).show();
// Log.e("COUNT::::", count + "");
}
}
});
}
#Override
public int getItemCount() {
return catList.size();
}
Because every time you create new arraylist in loop.
Do it in this way.
holder.btnIncrese.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int mPosition = (int) v.getTag();
Log.e("mPosition~", mPosition + "~" + position);
count = catList.get(mPosition).getCount() + 1;
filterList = new ArrayList<FilteredCategorymodel>();
for (int i = 0; i < catList.size(); i++) {
filterList.add(catList.get(i));
}
basketCount = basketCount + 1;
catList.get(mPosition).setCount(count);
holder.mQuantity.setText(Integer.toString(products.getCount()));
ProductActivity.updateSum(basketCount);
}
});
From this too less information, I guess You are trying to add some values to Your filterList. The problem is, that everytime Your are going through the loop, You are creating a new ArrayList:
for (int i = 0; i < catList.size(); i++) {
filterList = new ArrayList<FilteredCategorymodel>();
filterList.add(catList.get(i));
}
You have to init the filterList first, don´t do this inside the loop. Your loop must look like this:
for (int i = 0; i < catList.size(); i++) {
filterList.add(catList.get(i));
}
it´s also important what You trying to reach. If You just want to fill a new list if the button is clicked, then init Your list inside onButtonClick outside the loop. But if You want to fill that list again and again and the values should persist, then init the list inside Your constructor.
But also, in Your case, this will not work, because filterList is from type "FilteredCategoryModel" and catList is from type "Product". You cannot fill an ArrayList with a wrong type.
If you want to add one ArrayList data into another you don't need to use loop, Use addAll() of ArrayList. Please check below example.
ArrayList<YourClass> a = new ArrayList<>();
ArrayList<YourClass> b = new ArrayList<>();
b.addAll(a);
It will add all data of b into a.
How to populate AlertDialog from Arraylist.
My Arraylist something like this :
{ Brand=Weber,
Category=Urethane,
Code=Wpu-01,
Description=Black,
Quantity=5;
Brand=Weber,
Category=Urethane,
Code=Wpu-02,
Description=White,
Quantity=10}
And I want to show that in alertdialog is something like this
Product Details
Weber Urethane Wpu-01 Black 5
Weber Urethane Wpu-02 White 10
then a button ("CLOSE")
Please help me . Thanks in advance.
This the code
public void updateJSONdata() {
orderlist = new ArrayList<HashMap<String, String>>();
JSONObject json = jParser.getJSONFromUrl(PRODUCTLIST_URL);
try {
order = json.getJSONArray(GET_PRODUCT);
for (int i = 0; i < order.length(); i++) {
JSONObject c = order.getJSONObject(i);
String id = c.getString(GET_ID);
String brand = c.getString(GET_BRAND);
String category = c.getString(GET_CATEGORY);
String description = c.getString(GET_DESCRIPTION);
String code = c.getString(GET_CODE);
String quantity = c.getString(GET_QUANTITY);
String unit = c.getString(GET_UNIT);
String unitprice = c.getString(GET_UNITPRICE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(GET_ID,id);
map.put(GET_BRAND, brand);
map.put(GET_CATEGORY, category);
map.put(GET_DESCRIPTION, description);
map.put(GET_CODE, code);
map.put(GET_QUANTITY, quantity);
map.put(GET_UNIT, unit);
map.put(GET_UNITPRICE, unitprice);
orderlist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
StringBuilder sb = new StringBuilder();
for (HashMap<String,String> product:orderList){
for (Map.Entry entry:product.entrySet()){
sb.append(entry.getValue()).append(" ");
}
}
String msg = sb.toString();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Product details")
.setMessage(msg)
.setCancelable(false)
.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create().show();
To iterate through your ArrayList with HashMap and show the data on an AlertDialog, try something like:
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
StringBuilder sb = new StringBuilder();
for (HashMap map : list) {
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
sb.append(((Map.Entry) it.next()).getValue()).append(" ");
}
sb.append("\n"); // Use this if you want a line break.
}
String msg = sb.toString();
new AlertDialog.Builder(this)
.setTitle("Product details")
.setCancelable(false)
.setMessage(msg)
.setPositiveButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// Do something.
dialogInterface.dismiss();
}
}).show();
This will show all the information in one AlertDialog.
If you really want to show them all in one single line, remove this line of code:
sb.append("\n"); // Use this if you want a line break.
I checked other similar tags with almost same title. Those answers were not relevant
When setting element at one position of array, both the elements have the same value.
public class LogActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
startStopButton = (Button) findViewById(R.id.btnStart);
loggingStatusText = (TextView) findViewById(R.id.logStatusText);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
sensorValues=new ArrayList<float[]>(sensorList.size());
sensorValsArray=new float[sensorList.size()][];
sensorNameList = new ArrayList<String>();
selectedSensorNames = new ArrayList<String>();
for (Sensor itemSensor : sensorList)
{
if (itemSensor != null)
{
sensorNameList.add(itemSensor.getName());
}
}
showSensorList();
}
private void showSensorList()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setMultiChoiceItems((CharSequence[]) sensorNameList
.toArray(new CharSequence[sensorNameList.size()]),
new boolean[sensorNameList.size()],
new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked)
{
if (isChecked)
{
if (!selectedSensorNames.contains(sensorNameList
.get(whichButton)))
selectedSensorNames.add(sensorNameList
.get(whichButton));
} else
{
if (selectedSensorNames.contains(sensorNameList
.get(whichButton)))
{
selectedSensorNames.remove(sensorNameList
.get(whichButton));
}
}
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
listeners=new SensorEventListener[selectedSensorNames.size()];
float[] tempVals = new float[] { 0, 0, 0 };
for (int i = 0; i < selectedSensorNames.size(); i++)
{
sensorValsArray[i]=tempVals;
}
showRateList();
}
});
builder.setCancelable(false);
builder.create().show();
}
void registerSensors()
{
for (Sensor sensor : sensorList)
{
if (selectedSensorNames.contains(sensor.getName()))
{
mSensorManager.registerListener(listeners[selectedSensorNames.indexOf(sensor.getName())], sensor, selectedDelay);
}
}
}
class SchedulerTask extends TimerTask
{
/*
* The task to run should be specified in the implementation of the
* run() method
*/
public void run()
{
logSensorData();
}
}
private void createLog(String fileName)
{
File root = getExternalFilesDir(null);// Get the Android external
// storage directory
Date cDate = new Date();
String bstLogFileName = fileName;
bstLogFile = new File(root, bstLogFileName);// Construct a new file for
// using the specified
// directory and name
FileWriter bstLogWriter;
logScheduler = new Timer();// Create a new timer for updating values
// from content provider
logScheduler.schedule(new SchedulerTask(),
LOG_TASK_DELAY_IN_MILLISECONDS,
getLogPeriodInMilliSeconds(selectedDelay));
}
public void logSensorData()
{
Date stampDate = new Date();
String LogPack ="\r\n";
for (int count=0;count<selectedSensorNames.size();count++)
{
LogPack += sensorValsArray[count][0] + "," + sensorValsArray[count][1] + "," + sensorValsArray[count][2] + ",";
}
LogPack += "\r\n";
try
{
F_StreamWriter.write(LogPack);
F_StreamWriter.flush();
}
catch (IOException e)
{
}
catch (NullPointerException e)
{
}
}
public void startStopLog(View v)
{
if (startStopButton.getText().equals("Start"))
{
createSensorListeners();
registerSensors();
showFilenameDialog();
} else if (startStopButton.getText().equals("Stop"))
{
stopLog();
}
}
public void startLog(String fileName)
{
createLog(fileName);
}
public void stopLog()
{
logScheduler.cancel();
logScheduler.purge();
for(int i=0;i<listeners.length;i++)
mSensorManager.unregisterListener(listeners[i]);
}
private void showFilenameDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_text_input_dialog);
dialog.setCancelable(true);
final EditText fileNameInput = (EditText) dialog
.findViewById(R.id.fileNameText);
Button button = (Button) dialog.findViewById(R.id.okButton);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startLog(nameInput);
dialog.dismiss();
}
});
dialog.show();
}
private void createSensorListeners()
{
listeners=new SensorEventListener[selectedSensorNames.size()];
for (int i = 0; i < selectedSensorNames.size(); i++)
{
listeners[i]=new SensorEventListener()
{
#Override
public void onSensorChanged(SensorEvent event)
{
sensorValsArray[selectedSensorNames.indexOf(event.sensor.getName())]=event.values;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
};
}
}
}
When index is 0, when set command is executed, it also changes the the value at index position '1'.
Can anyone help me with this?
Thanks in Advance,
Dheepak
When index is 0, when set command is executed, it also changes the the value at index position '1'. Can anyone help me with this?
You are definitely mistaken as to what it is causing this. Setting the value at one position of an ArrayList WILL NOT mysteriously cause the value at another position to change. It simply does not work like that.
The effect you are observing will be due to something else:
maybe the value of index is not what you expect
maybe the value of event.values is not what you expect. (Maybe you've made a mistake in the way that you create the Event objects, and they are all sharing one float[] object.)
maybe the value at position 1 was already that value
maybe you've got multiple threads updating the sensorValues list.