I am doing quize app. In this app questions wont be generate duplicates. so I am using code like int value=random.nextInt(10-1)+1.When i submit the answer random number will generate newly so generating duplicates.How can i compare previous random value with new random values every time ?
Generate from 1 to 10 and store in a list
Shuffle the list of generated numbers
Keep removing from the list
List<Integer> list = new LinkedList<Integer>();
for (int i = 1; i <= 10; i++) {
list.add(i)
}
Collections.shuffle(list);
int value= list.remove(0);
.......
value= list.remove(0);
and so on...
Check this also : Java - generate Random range of specific numbers without duplication of those numbers - how to?
Also storing in a HashMap and checking is a smart way like the other answer says. But this can cause a lot more clashes, since everytime you try to add a duplicate to the HashMap you fail and you have to generate a new one again. But generating all at once and shuffling doesnt cause this. But since the input set is small(10) this collision might not happen too much(depending on the randomness, or maybe it happens too much?) and the O(1) access to the map elements for comparison will help.
Store value in a hashmap and then check if it's already there. If there reroll.
Here is code which i was using at my project. Full source code is
here
package com.banglardin.test_code;
import android.app.*;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import com.banglardin.test_code.*;
import java.util.*;
public class MainActivity extends Activity {
protected SharedPreferences preference;
protected Questions questionObject;
protected TextView textView;
protected Button buttonView, cleanButton;
protected ArrayList<String> ques_array;
protected final String KEY="Key124";
protected int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
//intilized Question and preference
questionObject = new Questions();
preference = getSharedPreferences(KEY,Context.MODE_WORLD_WRITEABLE);
// get array from question object
try{
ques_array= questionObject.getQestions(getApplicationContext());
}catch(Exception e){
e.printStackTrace();
}
// intilized views
textView = (TextView)findViewById (R.id.question);
buttonView = (Button) findViewById (R.id.button);
cleanButton = (Button) findViewById (R.id.button_clean);
textView.setTextSize(18.33f);
buttonView.setTextSize(18.00f);
cleanButton.setTextSize(18.00f);
// set onclickListener on button view
buttonView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
int set = 0;
if(i < 6){
while(set == 0){
String history = getString(KEY); // <0>
Random r = new Random();
int id = r.nextInt(ques_array.size());
String s_id= "<"+ String.valueOf(id) + ">"; // ex : <0>
if( !history.contains(s_id)){
textView.setText(ques_array.get(id));
setString(KEY, (history + s_id)); // ex : <0> + <3> = <0><3>;
set = 67;
i++;
}
}
}
else if(i>=6){
textView.setText(getResources().getString(R.string.e2));
Toast.makeText(MainActivity.this,"Questions are not available any more",2).show();
}
}
}
);
// set onclickListener on button view
cleanButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
setString(KEY, "<-0>");
}
}
);
}
#Override
public void onBackPressed(){
if(preference != null){
setString(KEY, ("<-0>"));
finish();
}
super.onBackPressed();
}
/** Get String value from preference */
private String getString(String KEY){
if(preference != null){
return preference.getString(KEY,"<-33>");
}
else{
return null;
}
}
/** Put String value to preference */
private void setString(String KEY, String value){
if(preference != null){
SharedPreferences.Editor edit = preference.edit();
edit.putString(KEY, value);
edit.commit();
}
}
/** Class that gives us all questions */
class Questions{
protected ArrayList<String> data;
public ArrayList<String> getQestions(Context c) throws Exception{
data = new ArrayList<String>();
Resources res= c.getResources();
String qes[] ={
res.getString(R.string.q1) , //0
res.getString(R.string.q2) , //1
res.getString(R.string.q3) , //2
res.getString(R.string.q4) , //3
res.getString(R.string.q5) , //4
res.getString(R.string.q6) , //5
res.getString(R.string.q7) , //6
};
// add all the strings one by one
for(String i : qes){
data.add(i);
}
return data;
}
}
}
use 'HashSet' class in the main property of this class is they contain set of different values mean no value is repeated in it......
so u can generate random no. and add it in set like this
Random r = new Random();
int i = r.nextInt(100);
HashSet<int> s = new HashSet<int>();
s.add(i);
generat random number and add it inti hashset and use it....
an in nextInt parameter have to give maximum no. range...
example code as follows:
Random r = new Random();
//declare a hash set
HashSet set = new HashSet();
for(int i=0;i<50;i++)
{
set.add(r.nextInt(100));
}
// create an iterator
Iterator iterator = set.iterator();
// check values
while (iterator.hasNext()){
System.out.println("Value: "+iterator.next() + " ");
}
Related
We are trying to use this array of integers in other methods. Setting the final shuffled Array to a global variable has become next to impossible. We have set other variable as global. The goal here is to have a new int [] fix array every time a button is clicked. We have been able to generate a random int [] ar but can not utilize the array in other methods. So our questions after making the random int [] ar how can we use it in the onClickBtnOne method? Code with comments below
public class MainActivity extends AppCompatActivity {
Button btn1,btn2,btn3,btn4,btn5,btn6;
String T1,T2,T3,T4,T5,T6;
int test[] = new int[7];
int count = 0;
int v1,v2,v3,v4,v5,v6;
int[] fix = {3,2,1,4,6,5};
// Trying to not use above values
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
main(null);
}
// end onCeate
public static void main(String args[]) {
int [] fix = {1,2,3,4,5,6};
shuffleArray(fix);
// Want to USE this fix shuffleArray
//==================================
for (int i = 0; i < fix.length; i++) {
System.out.print(fix[i] + ",");
}
System.out.println();
}
// Implementing Fisher–Yates shuffle
static void shuffleArray(int [] ar) {
// If running on Java 6 or older, use `new Random()` on RHS here
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void onClickBtnOne(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
count = count + 1;
v1 = count;
test[v1] = count;
if(fix[0] == test[v1]){
// Need a global fix[] here
// =========================
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
The array you are trying to use does not have an add method you need to put the values in from another variable like this ar[i] = a; So if you use this type of Array declaration List value = new ArrayList<>(); where you declared the other global variable life will be much easier. Modified code below
This will do the shuffle NOTICE value.clear() without this the List will grow each time it is initialized
public void shf(View view){
value.clear();
for (int i = 1; i <= 6; i++) {
value.add(i);
}
Collections.shuffle(value);
}
And here is your test method call value.get(index) Arrays are ZERO based
public void on1(View view){
btn1.setBackgroundColor(getColor(R.color.color_Red));
btn1.setEnabled(false);
if(value.get(0) == 1){
T1 = "true";
if(T1.matches("true")){
btn1.setBackgroundColor(getColor(R.color.color_Yellow));
}
}else {
T1 = "false";
}
}
I want to pass value from drawable folder . I know the way how to pass value from draw able but have less knowledge to modify below code . In this code all players value are fetched from "Assets" . and I want to pass from drawable . drawable folder has two value , one is " player" folder and another is background image ,some icons. I am not sure about subfolder in drawable will work or not . If not then how I'll exclude background image , icons. I can pass drawable value using array like player[] ={R.drawable.A, R.drawable.B....} . Still unable to modify this code . I am feeling really helpless :(
public class QuizGame extends Activity {
//String used when logging error messages
private static final String TAG = "QuizGame Activity";
//Instance Variables
private List<String> fileNameList; // player file names
private List<String> quizPlayersList; // names of players in quiz
private String correctAnswer; // current correct answer
private int totalGuesses; // number of guesses
private int correctAnswers; // number of correct guesses
private int guessRows; // number of rows displaying choices
private Random random; // random number generator
private Handler handler; // used to delay loading of next player
private Animation shakeAnimation; // animation for incorrect answers
private TextView answerTextView;
private TextView questionNumberTextView;
private ImageView faceImageView;
private TableLayout buttonTableLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fileNameList = new ArrayList<String>(); // list of image file names
quizPlayersList = new ArrayList<String>(); // players in quiz
guessRows = 3; // defaulted to one row of choices
random = new Random(); // initialize the random number generator
handler = new Handler(); // used to perform delayed operations
// get references to the GUI components
questionNumberTextView = (TextView) findViewById(R.id.questionNumberTextView);
answerTextView = (TextView) findViewById(R.id.answerTextView);
faceImageView = (ImageView) findViewById(R.id.faceImageView);
buttonTableLayout = (TableLayout) findViewById(R.id.buttonTableLayout);
// set questionNumbers Text
questionNumberTextView.setText(
getResources().getString(R.string.question) + " 1 " +
getResources().getString(R.string.of) + " 10");
// load the shake animations used to animate incorrect answers
shakeAnimation = AnimationUtils.loadAnimation(this, R.anim.incorrect_shake);
shakeAnimation.setRepeatCount(3); // animation repeats 3 times
// start a new quiz
resetQuiz();
} //end onCreate method
// set up and start the next quiz
private void resetQuiz(){
// use the AssetManager to get the player image
// file names for the app
AssetManager assets = getAssets();
fileNameList.clear(); // clear the list
// get list of all player names in this region
String[] paths = null;
try {
paths = assets.list("Players");
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "Error loading ", e);
}
for(String path : paths)
fileNameList.add(path.replace(".jpg", ""));
correctAnswers = 0; // reset number of correct answers
totalGuesses= 0; // reset number of guesses
quizPlayersList.clear(); // clear prior list of quiz countries
// add 10 random file names to the quiz list
int playerCounter = 1;
int numberOfPlayers = fileNameList.size();
while(playerCounter <= 10){
int randomIndex = random.nextInt(numberOfPlayers);
//get random file name
String fileName = fileNameList.get(randomIndex);
//if region is enabled and hasnt been chosen
if(!quizPlayersList.contains(fileName)){
quizPlayersList.add(fileName);
++playerCounter;
}
}
loadNextPlayer(); //start quiz by loading next player
}
// after user guesses a correct player, load the next one
private void loadNextPlayer(){
//get the filename of the next flag and remove it from the list
String nextImageName = quizPlayersList.remove(0);
correctAnswer = nextImageName; //update correct answer
answerTextView.setText(""); //clear the answerTextView
//display the number of the current question in the quiz
questionNumberTextView.setText(
getResources().getString(R.string.question) + " " +
(correctAnswers + 1) + " " +
getResources().getString(R.string.of) + " 10");
//extract the region from the next images name
String region = "Players";
//use AssetManager to load next image from assets folder
AssetManager assets = getAssets(); // get apps Asset Manager
InputStream stream; // used to read in player names
try{
//get an InputStream to the asset representing the next flag
stream = assets.open(region + "/" + nextImageName + ".jpg");
//load the asset as Drawable and display on the flagImageView
Drawable flag = Drawable.createFromStream(stream, nextImageName);
faceImageView.setImageDrawable(flag);
}
catch (IOException e){
Log.e(TAG, "Error loading " + nextImageName, e);
}
//clear prior answer buttons from tablerows
for (int row = 0; row < buttonTableLayout.getChildCount(); row++)
((TableRow) buttonTableLayout.getChildAt(row)).removeAllViews();
Collections.shuffle(fileNameList); //shuffle file names
//put the correct answer at the end of the fileNameList
int correct = fileNameList.indexOf(correctAnswer);
fileNameList.add(fileNameList.remove(correct));
//get a reference to the LayoutInflator Service
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// add 3, 6, or 9 answer Buttons based on the value of guessRows
for (int row = 0; row < guessRows; row++){
TableRow currentTableRow = getTableRow(row);
//place Buttons in currentTableRow
for (int column = 0; column < 3; column++){
//inflate guess_button.xml to create new Button
Button newGuessButton =
(Button) inflater.inflate(R.layout.guess_button, null);
//get player name and set it as newGuessButtons text
String fileName = fileNameList.get((row * 3) + column);
newGuessButton.setText(getPlayerName(fileName));
//register answerButton listener to respond to clicks
newGuessButton.setOnClickListener(guessButtonListener);
currentTableRow.addView(newGuessButton);
}
}
//randomly replace one Button with the correct answer
int row = random.nextInt(guessRows);
int column = random.nextInt(3);
TableRow randomTableRow = getTableRow(row);
String playerName = getPlayerName(correctAnswer);
((Button) randomTableRow.getChildAt(column)).setText(playerName);
} // end loadNextPlayer method
// return the specified TableRow
private TableRow getTableRow(int row){
return (TableRow) buttonTableLayout.getChildAt(row);
}
// parses the player file name and returns the player name
private String getPlayerName(String name){
return name.substring(name.indexOf('-') + 1).replace('-', ' ');
}
// method submitGuess called when user selects an answer
private void submitGuess (Button guessButton){
String guess = guessButton.getText().toString();
String answer = getPlayerName(correctAnswer);
++totalGuesses; //increment the number of guesses made
if (guess.equals(answer)){
++correctAnswers; // increment number of correct answers
//display Correct answer in answerTextView
answerTextView.setText(answer + "!" );
answerTextView.setTextColor(getResources().getColor(R.color.correct_answer));
disableButtons(); //disable all answer Buttons
// if user has guessed 10 correct players
if (correctAnswers == 10){
//create new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.reset_quiz);
//set the AlertDialogs message to display the game results
builder.setMessage(String.format("%d %s, %.02f%% %s", totalGuesses,
getResources().getString(R.string.guesses),
(1000 / (double) totalGuesses),
getResources().getString(R.string.correct)));
builder.setCancelable(false);
//add reset quiz button
builder.setPositiveButton(R.string.reset_quiz,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
resetQuiz();
} // end onClick
} // end anonymous inner class
); //end call to setPositiveButton
// create AlertDialog from the Builder
AlertDialog resetDialog = builder.create();
resetDialog.show();
} // end if
else // answer is correct but game isnt over
{
//load the next flag after a one second delay
handler.postDelayed(
new Runnable()
{
#Override
public void run(){
loadNextPlayer();
}
}, 1000); // 1000 milliseconds for 1 second delay
} // end else
} // end if
else // answer was incorrect
{
//play the animation
faceImageView.startAnimation(shakeAnimation);
//display "Incorrect" in red
answerTextView.setText(R.string.incorrect_answer);
answerTextView.setTextColor(getResources().getColor(R.color.incorrect_answer));
guessButton.setEnabled(false); // disable the incorrect answer
}
} // end submitGuess method
// method to disable all answer Buttons
private void disableButtons(){
for (int row = 0; row < buttonTableLayout.getChildCount(); row++){
TableRow tablerow = (TableRow) buttonTableLayout.getChildAt(row);
for(int i = 0; i < tablerow.getChildCount(); i++){
tablerow.getChildAt(i).setEnabled(false);
}
}
}
// create constants for each menu id
private final int CHOICES_MENU_ID = Menu.FIRST;
// called when the user accesses the options menu
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
// add options to the menu
menu.add(Menu.NONE, CHOICES_MENU_ID, Menu.NONE, R.string.choices);
return true; // display the menu
}
// called when the user selects an option from the menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// switch the menu id of the user selected option
switch (item.getItemId())
{
case CHOICES_MENU_ID:
//create a list of the possible number of answer choices
final String[] possibleChoices = getResources().getStringArray(R.array.guessesList);
//create an AlertDialog Builder and set its title
AlertDialog.Builder choicesBuilder = new AlertDialog.Builder(this);
choicesBuilder.setTitle(R.string.choices);
//add possibleChoices items to the Dialog and set the
// behavior when one of the items is clicked
choicesBuilder.setItems(R.array.guessesList,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// update guessRows to reflect user choice
guessRows = Integer.parseInt(possibleChoices[item].toString()) / 3;
resetQuiz();
}
});
// create AlertDialog from the Builder
AlertDialog choicesDialog = choicesBuilder.create();
choicesDialog.show();
break;
} // end switch
return super.onOptionsItemSelected(item);
}// end method onOptionsItemSelected
Because my log command kicks out a "4" I am guessing it is:
word.getnewword();
that is returning the null pointer exception, but why?
The aim of the code is to have a class that will hold different letters in a word for me to then animate each letter in the word separately then change the word to a random new one from a list in the class. I am using char for each letter instead of a string for the word or each letter, is that ok also?
package com.xyz.letters;
import ......abreviated
public class letters extends Activity {
private Animals word;
boolean gameover = false;
private AdView adView;
TextView tva;
TextView tvb;
TextView tvc;
TextView tvd;
TextView tve;
TextView tvf;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letters);
Log.e("main", "xml loaded fine");
tva = (TextView) findViewById(R.id.texta);
tvb = (TextView) findViewById(R.id.textb);
tvc = (TextView) findViewById(R.id.textc);
tvd = (TextView) findViewById(R.id.textd);
tve = (TextView) findViewById(R.id.texte);
tvf = (TextView) findViewById(R.id.textf);
Log.e("main", "textview pre-setup complete");
Log.e("main", "4");
word.getnewword();
Log.e("main", "gotword " + word.getwordchosennumber());
setletters();
Log.e("main", "set letters ok");
......etc
My class:-
package com.xyz.letters;
import java.util.Random;
import android.util.Log;
public class Animals {
private int wordchosen;
private int length;
private char l1;
private char l2;
private char l3;
private char l4;
private char l5;
private char l6;
public Animals() {
this.wordchosen = 0;
this.length = 3;
this.l1 = 'a';
this.l2 = 'b';
this.l3 = 'c';
this.l4 = 'a';
this.l5 = 'b';
this.l6 = 'c';
}
public void getnewword() {
Log.e("animals", "0");
Random ran = new Random();
Log.e("animals", "1");
wordchosen = ran.nextInt(2);
Log.e("animals", "2");
switch (wordchosen) {
case 0:
length = 3;
l1 = 'a';
l2 = 'n';
l3 = 't';
break;
case 1:
length = 4;
l1 = 'b';
l2 = 'a';
l3 = 'l';
l4 = 'l';
break;
case 2:
length = 3;
l1 = 'b';
l2 = 'a';
l3 = 't';
break;
default:
length = 0;
break;
}
}
public int getwordchosennumber()
{
return this.wordchosen;
}
public int getlength()
{
return this.length;
}
public int getl1()
{
return this.l1;
}
public int getl2()
{
return this.l2;
}
public int getl3()
{
return this.l3;
}
public int getl4()
{
return this.l4;
}
public int getl5()
{
return this.l5;
}
public int getl6()
{
return this.l6;
}
}
Because, word has null value. The exception null pointer exception itself specify its meaning that, you want to access some object, which has null reference.
Declared here
private Animals word;
Initially, it has null reference, until you won't do something like
word = new Animals(); // assign Animals reference
You never initialize word. On the line before the error (or in the initial declaration), use new:
word = new Animals(); // The line to insert.
word.getnewword();
On future questions, when you get an exception or force close, please post the full LogCat stack trace (red text in your log output), to help us find the problem quicker.
In the OnCreate after
Log.e("main", "textview pre-setup complete");
add
word = new Animals();
You should create the object of the class like
word = new Animals();
now, use this object to access the public methods and variable of Animals class.
word.getnewword();
You're getting a NullPointerException because the variable "word" wasn't initialized. Android is a little bit strange when it comes to working with variables. If you don't initialize the variable in the onCreate method (or some method that is called from the onCreate method) before you call the variable then you will get a NullPointerException because the JVM doesn't know what the value of that variable is. It's kind of like regular java code that has a main method - if you call a variable that hasn't been inialized in the main method you'll get a NullPointerException.
To fix your code simply put this in the onCreateMethod before you make any calls to the variable:
word = new Animals();
After that you can do what you need with the variable.
I'll tell you the aim of this part of my app. I've got a SQLite dB which has 3 columns. First is "Quantity", Second is "Product" and third is "Price". Well, what i want to do is to get the whole dB and send it by email.
This is what i have right now:
public class Visual extends Activity {
TextView tv;
Button sqlGetInfo;
long l ;
long b=1;
int c,i;
String returnedQuantity ,returnedProduct ,returnedPrice;
String[] filas;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.visual);
tv = (TextView) findViewById(R.id.tvSQLinfo);
sqlGetInfo = (Button) findViewById(R.id.EnviarPedido);
SQLManager info = new SQLManager(this);
info.open();
String data= info.getData();
info.close();
tv.setText(data);
Up to here, my code works fine, it displays the data in the textView. Here is the problem. My dB has a maximum of 15 rows. What i want to do is to store each row in a position of a string array (filas). First row = filas(0), second row = filas(1)...in order to be able to pass this array to another activity. If the array has less than 15 rows i think it would give an exception. So it's the time to open the other activity.
final SQLManager hon = new SQLManager(this);
sqlGetInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (i = 1; i < 15; i++) {
try{
l = (long) i;
hon.open();
returnedQuantity = hon.getQuantity(l);
returnedProduct = hon.getProduct(l);
returnedPrice = hon.getPrice(l);
hon.close();
c=(int)(l-b);
filas[c]="" + returnedQuantity+" "+ returnedProduct+" "+ returnedPrice + "\n";
}catch (Exception e){
i = 16;
l = (long) i;
Intent abrePedidos = new Intent(Visual.this, Pedidos.class);
abrePedidos.putExtra("pedidoCompleto", filas);
startActivity(abrePedidos);
}
}
}
});
}
}
The other activity is this:
public class Pedidos extends Activity {
String[] filas;
long numProd;
boolean end;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
filas=getIntent().getStringArrayExtra("pedidoCompleto");
String subject = "Pedido a Domicilio";
String cabecera = "Unid. Producto Precio\n\n";
String[] emails = {"ulrickpspgo#gmail.com"};
String message = cabecera + filas;
Intent emailIntent = new Intent (android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emails);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, message);
emailIntent.setType("plain/text");
startActivity(emailIntent);
}
}
What I get as the message of my email is "null".
I think you problem is the following: you never initialize String[] filas;. This means that it remains null all the time. Afterwards you go to your code:
try {
l = (long) i;
hon.open();
returnedQuantity = hon.getQuantity(l);
returnedProduct = hon.getProduct(l);
returnedPrice = hon.getPrice(l);
hon.close();
c=(int)(l-b);
// The next line throws null pointer exception
filas[c]="" + returnedQuantity+" "+ returnedProduct+" "+ returnedPrice + "\n";
} catch (Exception e) { // here you catch the null pointer exception
i = 16;
l = (long) i;
Intent abrePedidos = new Intent(Visual.this, Pedidos.class);
abrePedidos.putExtra("pedidoCompleto", filas); //filas is still null
startActivity(abrePedidos);
}
I have added comments for some of your lines. Why do you call the next activity only in the catch clause? Having so much code in the catch clause is very bad practise it is called expection handling. don't do it. Otherwise if you initialize your array (which I am not sure you have not already done, but this is my guess what the exception you hide is) you should be good to go. Do not forget to place the code outside the catch block, though, because I do not expect any exceptions after the modification.
EDIT I do not like the way you iterate over the elements in the database. I am not familiar with the SQLManager class you use. However the standard Android way is very similar to the JDBC model. You do a query and it returns a cursor over the results. See example of using cursors and SQLitehleprs over here: http://www.higherpass.com/Android/Tutorials/Accessing-Data-With-Android-Cursors/2/
I have some problem in updating the values to hash-table,here is my problem i will explain it clearly.
1.I have getting the response from server,i am adding the values to layout,by using layout Layout-Inflater.
2.in our application we have streaming request.when the streaming request is turned on the values need to be updated regularly.
storing values in hash-tables
Hashtable<String, View> indicesHashtable = new Hashtable<String, View>();
For(Step 1)code i have written belowthe code.
private void addIndices(LinearLayout parent, final String key,final String value) {
LayoutInflater factory = LayoutInflater.from(mContext);
final View row = factory.inflate(R.layout.indices_values, null);
final TextView keyTextView = (TextView) row.findViewById(R.id.txtCompany);
final TextView valueTextView = (TextView) row.findViewById(R.id.txtIndex);
final Button iconImageView = (Button) row.findViewById(R.id.btnIcon);
row.setBackgroundResource(android.R.drawable.list_selector_background);
if (value.length() > 0) {
keyTextView.setText(Html.fromHtml("<b>"+indices.get(key)+"</b>"));
valueTextView.setText(Html.fromHtml(value));
if(quoteArrowIconId != -1)
iconImageView.setBackgroundResource(quoteArrowIconId);
else
iconImageView.setBackgroundDrawable(null);
}else{
keyTextView.setText(Html.fromHtml(key));
}
indicesHashtable.put(key, row);
parent.addView(row);
}
For(Step 2)i need help from you guys.
i have written code..that i have shown below.
private void handleResponseOfResponses(ResponseParser response) {
Hashtable responses = (Hashtable) response.getValue(Response_890.RESPONSES);
String[] symbols = new String[responses.size()];
int index = 0;
indicesHashtable.clear();
for(int i =indicesSymbols.length-1; i >= 0; i--){
Enumeration e = responses.keys();
while (e.hasMoreElements()) {
ResponseParser subResponse = (ResponseParser) responses.get(e.nextElement());
if (subResponse.getResponseCode() == ResponseCodes.QUOTES_RESPONSE) {
String[] quoteProperties = (String[]) subResponse.getValue(Response_312.QUOTES_KEY);
if(quoteProperties[0].equalsIgnoreCase(indicesSymbols[i])){
// symbolTable.put(quoteProperties[0].toUpperCase(), index);
symbols[index++] = quoteProperties[0];
String value = quoteValue(quoteProperties);
For displaying the values coming for response i have added (AddIndices)method
addIndices(linear_Indices, quoteProperties[0], value);
}
}
}
}
autoscroll();
indicesStreamerClient = new StreamerClient(indicesSymbols){
#Override
public void onStreamDataReceived(QuoteData quoteData) {
System.out.println("onStreamDataReceived () -> "+quoteData.getSymbol());
HERE I NEED TO ADDED ANOTHER METHOD FOR UPDATING THE VALUES..HOW I CAN WRITE THE CODE.
};
};
Streamer.getInstance(mContext).registerStramerClient(indicesStreamerClient);
}
Guys i am fresher as well as new to andriod.
Thanks in advance!!!!!!