android firebase retrieving data more than once - android

I'm doing a project right now that is supposed to be a math teaching app for kids.
I'm using firebase as my database to save the user names and password and also to save the questions and their answers.
I have a problem retreiving the question and the answers from the database and display it on the buttons and textview because it appears that the listener for single value event is triggered only when the class is done with all the other commands and i need to use this listener for every question i have.
My database:
My code so far:
ArrayList <Integer> list = new ArrayList<Integer>();
for (int i=1; i<11; i++) {
list.add(new Integer(i));
}
Collections.shuffle(list);
for (int i=0; i<5; i++) {
ref2 = ref.child(list.get(i).toString());
Questions.cont = false;
getQuestionsFromDb(ref2);
questionView.setText(Questions.question);
button1.setText(Questions.ans1);
button2.setText(Questions.ans2);
button3.setText(Questions.ans3);
button4.setText(Questions.ans4);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Questions.cont = true;
int ans = getAns(Questions.question);
Button b = (Button)v;
int buttonText = Integer.parseInt(b.getText().toString());
if(ans == buttonText) {
Questions.points++;
}
}
});
}
questionView.setText(Questions.points);
// end of for loop
}
private void getQuestionsFromDb(Firebase ref2) {
// TODO Auto-generated method stub
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
System.out.println("aaa");
String question = (String) snapshot.child("question").getValue();
String ans1 = snapshot.child("ans1").getValue().toString();
String ans2 = snapshot.child("ans2").getValue().toString();
String ans3 = snapshot.child("ans3").getValue().toString();
String ans4 = snapshot.child("ans4").getValue().toString();
Questions.question = question;
Questions.ans1 = ans1;
Questions.ans2 = ans2;
Questions.ans3 = ans3;
Questions.ans4 = ans4;
}
#Override
public void onCancelled(FirebaseError arg0) {
// TODO Auto-generated method stub
}
});
}
private int getAns(String ansString) {
// TODO Auto-generated method stub
String[] parts = ansString.split("\\b");
String ans;
if(parts.length == 5) {
ans = parts[0] + parts[1] + parts[2] + parts [3] + parts [4];
}
else {
ans = parts[0] + parts[1] + parts[2];
}
return Integer.parseInt(ans);
}
As you can see i'm also using outer class that have static variables in order to save the questions and the answers and use them out of the inner class.
I hope someone can help.

In your case you should add more listeners addListenerForSingleValueEvent() to get all the data you need or rewrite your logic using addValueEventListener. In that case your data will be actual at any time.

Related

Swipeable-Cards Adapter get Item Info

I m using this framework, I already trying many times for making this problem, but I cant do it. I already asking on stackoverflow but no one cant help me. Actually I m tried.
I m using this framework : https://github.com/kikoso/Swipeable-Cards
And I m using SimpleCardStackAdapter like this :
for (int i = 0; i < user.length(); i++) {
final JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
// adapter.add(new CardModel(name, email, image1));
//Set JSON Data in TextView
Log.i("image1image1image1image1", image1);
// CardModel cardModel = new CardModel(" cardModel", " CardModel", r.getDrawable(R.drawable.picture1));
card = new CardModel(name, email, image1);
card.setOnClickListener(new CardModel.OnClickListener() {
#Override
public void OnClickListener() {
Log.i("Swipeable Cards", "I am pressing the card");
// Intent no = new Intent(HomeListview.this, YayDetailActivity.class);
/// startActivity(no);
}
});
card.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
#Override
public void onLike(CardModel card) {
Log.i("Swipeable Cards", "I dislike the card");
}
#Override
public void onDislike(CardModel card) {
Log.i("Swipeable Cards", "I like the card");
// new sendNewYay().execute(sharedToken, card.getTitle());
Toast.makeText(getApplicationContext(), card.getDescription(), Toast.LENGTH_SHORT).show();
}
});
// I m added adapter
adapter.add(card);
mCardContainer.setAdapter(adapter);
}
At the onDislike method, I need to get item name.
in this line : new sendNewYay().execute(sharedToken, name);
I send the item name, But it dont work.
1.How can I get the item name, in this method?
2.I have two button, one of them for onLike method, another one for onDislike Method. Ho can I triggered this two method with my button?
Thank you.
Decleare two variable global as string
String itemname;
try {
JSONArray c = new JSONArray(user.toString());
for (int i = 0 ; i < c.length();i++) {
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
System.out.println("Position : " + "" + i + ""+ c.getString(i));
itemname = name.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Final itemname is " + itemname);

Error in Dijkstra algorithm in android

I am implementing the 'Dijkstra algorithm' in Android for making an app for Metro Network.
When I click on the button to show the path, it stops the app.
I have explicitly defined the graph to store in array adj[][].
MetroRoute class
public class MetroRoute extends Activity implements OnClickListener{
EditText source, destination;
TextView Route;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.metroroute);
source = (EditText) findViewById(R.id.etSource);
destination = (EditText) findViewById(R.id.etDest);
button = (Button) findViewById(R.id.bGetroute);
Route = (TextView) findViewById(R.id.tvRoute);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int count, i;
count = findpath(Integer.parseInt(source.getText().toString()), Integer.parseInt(destination.getText().toString()), path, sdist );
if(sdist!=0)
{
Route.setText("Shortest distance is : \n" + sdist);
Route.setText("Shortest Path is : ");
for( i=count;i>1;i--)
Route.setText(path[i] + " -> ");
Route.setText(path[i]);
}
else
Route.setText("There is no path from source to destination node\n");
}
int adj[][] = {{3,2,3,0,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
int MAX = 10, TEMP = 0, PERM =1, INFINITY = 9999, path[], sdist=0, n=5 ;
private class Node {
int predecessor[];
int dist[]; /*minimum distance of node from source*/
int status[];
}
int findpath(int s,int d,int path[],int sdist)
{
Node state = new Node();
int i, min=0, count=0, current, newdist, u, v ;
sdist=0;
/* Make all nodes temporary */
for(i=1;i<=n;i++)
{
state.predecessor[i]=0;
state.dist[i] = INFINITY;
state.status[i] = TEMP;
}
/*Source node should be permanent*/
state.predecessor[s]=0;
state.dist[s] = 0;
state.status[s] = PERM;
/*Starting from source node until destination is found*/
current=s;
while(current!=d)
{
for(i=1;i<=n;i++)
{
/*Checks for adjacent temporary nodes */
if ( adj[current][i] > 0 && state.status[i] == TEMP )
{
newdist=state.dist[current] + adj[current][i];
/*Checks for Relabeling*/
if( newdist < state.dist[i] )
{
state.predecessor[i] = current;
state.dist[i] = newdist;
}
}
}
/*Search for temporary node with minimum distance make it current node*/
min=INFINITY;
current=0;
for(i=1;i<=n;i++)
{
if(state.status[i] == TEMP && state.dist[i] < min)
{
min = state.dist[i];
current=i;
}
}
if(current==0) /*If Source or Sink node is isolated*/
return 0;
state.status[current]=PERM;
}
/* Getting full path in array from destination to source */
while( current!=0 )
{
count++;
path[count]=current;
current=state.predecessor[current];
}
/*Getting distance from source to destination*/
for(i=count;i>1;i--)
{
u=path[i];
v=path[i-1];
sdist+= adj[u][v];
}
return (count) ;
}
}
The easiest way to find the problem is to use the console of the adk to see the exceptions thrown by the device. When you start your app from your IDE (Eclipse, Android Studio) in a virtual device, or even your smartphone, you will get logcat-messages, which will contain the exceptions like for example the NullPointerException. You will then find the lines where the exception is thrown and then you can do some further testing (like writing some values to the console (System.Out.println(...) or System.err.println(...)).
You can post your log so we can take a look at it.
You may want to use my Dijkstra-implementation, too:
public static ArrayList<Integer> dijkstra(Graph graph, Integer orig,
Integer dest, TreeMap<Integer, Integer> distance,
ArrayList<Integer> nodesLeft) throws Exception
{
Iterator<Integer> iterator = graph.getNodes().iterator();
Integer next;
TreeMap<Integer, ArrayList<Integer>> paths = new TreeMap<Integer, ArrayList<Integer>>();
while (iterator.hasNext()) {
next = iterator.next();
distance.put(next, -1);
paths.put(next, new ArrayList<Integer>());
}
distance.put(orig, 0);
nodesLeft.addAll(Collections.unmodifiableCollection(graph.getNodes()));
while (!nodesLeft.isEmpty()) {
int u = nodesLeft.get(0);
Collection<Integer> edgesOfU = graph.getEdges(u);
Iterator<Integer> itEdgesOfU = edgesOfU.iterator();
int nextEdge;
while (itEdgesOfU.hasNext()) {
nextEdge = itEdgesOfU.next();
if (nodesLeft.contains(nextEdge)) {
int distU = distance.get(u);
if ((distance.get(nextEdge) == -1)
|| (distU + 1) < distance.get(nextEdge)) {
distance.put(nextEdge, distU + 1);
ArrayList<Integer> tmpList = paths.get(nextEdge);
for (int a : paths.get(u)) {
tmpList.add(a);
}
tmpList.add(nextEdge);
}
}
}
nodesLeft.remove(0);
}
return paths.get(dest);
}
I used some self-defined Graphs with the following Interface:
import java.util.Collection;
public interface Graph {
public Integer addNode();
public void removeNode(Integer id) throws Exception,
UnsupportedOperationException;
public Collection<Integer> getNodes();
public boolean addEdge(Integer orig, Integer dest) throws Exception;
public boolean removeEdge(Integer orig, Integer dest) throws Exception,
UnsupportedOperationException;
public Collection<Integer> getEdges(Integer orig) throws Exception;
}

Working Example to find the LCM of more than 2 Numbers

Android 2.3.3
I have written a program for calculating the LCM for more than 2 numbers, and it worked for me. I thought of sharing it, so that it might come in handy for those who are looking for it. This may not be the best solution, but, i did it according to my requirement. You can modify it to your need.
I have hard coded the input, and also my program uses ArrayLists to do the operations. You might want to change these.
Pre-Requisites ::: 1. Calculation of PrimeNumbers for the range of inputs.
public class PlusMinusActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText edtxtExpression;
Button btnLCM, btnGCD;
ArrayList<String> alPrimes = new ArrayList<String>(); // Contains List of Prime Numbers
ArrayList<String> alNumbers = new ArrayList<String>(); // Contains the input => Numbers for which LCM is to be determined
ArrayList<String> alResult = new ArrayList<String>(); // Contains the numbers that make up the LCM
String strExp = ""; // Temporary String to display the result
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtxtExpression = (EditText)findViewById(R.id.edtxtExpression);
btnLCM = (Button)findViewById(R.id.btnLCM);
btnGCD = (Button) findViewById(R.id.btnGCD);
btnLCM.setOnClickListener(this);
btnGCD.setOnClickListener(this);
addData();
strExp = alNumbers.toString();
System.out.println("strExp Value is ::: "+strExp);
}
private void addData() {
// TODO Auto-generated method stub
//alPrimes.add(String.valueOf(1));
alPrimes.add(String.valueOf(2));
alPrimes.add(String.valueOf(3));
alPrimes.add(String.valueOf(5));
alPrimes.add(String.valueOf(7));
alPrimes.add(String.valueOf(9));
alPrimes.add(String.valueOf(11));
alPrimes.add(String.valueOf(13));
alPrimes.add(String.valueOf(17));
alPrimes.add(String.valueOf(19));
alPrimes.add(String.valueOf(23));
alPrimes.add(String.valueOf(29));
alNumbers.add(String.valueOf(1));
alNumbers.add(String.valueOf(5));
alNumbers.add(String.valueOf(7));
alNumbers.add(String.valueOf(9));
System.out.println("alPrimes ::: "+alPrimes.toString());
System.out.println("alNumbers ::: "+alNumbers.toString());
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnLCM:
calculateLCM();
break;
case R.id.btnGCD:
calculateGCD();
break;
default:
break;
}
}
// Calculates LCM
private void calculateLCM() {
// TODO Auto-generated method stub
int i=0, count=0;
while(i < alPrimes.size())
{
count = 0;
int p = Integer.parseInt(alPrimes.get(i)); // Getting the element from PrimeNumbers List
System.out.println("Prime Number ::: "+p);
int j=0;
while(j < alNumbers.size())
{
int n = Integer.parseInt(alNumbers.get(j)); // Getting the number from Input List
System.out.println("Number ::: "+n);
if(n % p == 0 && n != 1)
{
count++; // Counts the number of integers that gets divided (% = 0) by that particular prime number
System.out.println("Count :::"+count);
}
j++;
}
if(count >= 2) // If two or more numbers, gets divided, then we do the division
{
alResult.add(String.valueOf(p)); // adding the prime number to Result list
System.out.println("Result ::: "+alResult.toString());
j=0;
while(j < alNumbers.size())
{
int n = Integer.parseInt(alNumbers.get(j));
System.out.println("Number ::: "+n);
if(n % p == 0)
{
int result = n/p;
System.out.println("Temp Result ::: "+result);
alNumbers.remove(j); // Replace the element by the result
System.out.println("After Removing ::: "+alNumbers.toString());
alNumbers.add(j, String.valueOf(result));
System.out.println("After Adding ::: "+alNumbers.toString());
}
j++;
}
i = -1; // iterate the Input list from the start
}
else if(count == 0 || count == 1)
{
boolean allPrimes = checkAllPrimes();
if(allPrimes)
{
break;
}
}
i++;
}
calculateResult();
}
// Calculates the result
private void calculateResult() {
// TODO Auto-generated method stub
int i=0;
while(i < alNumbers.size())
{
alResult.add(alNumbers.get(i));
i++;
}
int result = 1;
i=0;
while(i < alResult.size())
{
result *= Integer.parseInt(alResult.get(i));
i++;
}
edtxtExpression.setText("LCM of "+strExp+" is ::: "+result);
}
// Checks whether the elements in the ArrayList are all prime numbers
// returns true if all are prime
//
private boolean checkAllPrimes() {
// TODO Auto-generated method stub
int i=0;
boolean areAllPrimes = true;
while(i < alNumbers.size())
{
int n = Integer.parseInt(alNumbers.get(i));
if(! (alPrimes.contains(n) || n == 1))
{
areAllPrimes = false;
break;
}
i++;
}
return areAllPrimes;
}
private void calculateGCD() {
// TODO Auto-generated method stub
}
}
For the following input :::
alNumbers.add(String.valueOf(10));
alNumbers.add(String.valueOf(15));
alNumbers.add(String.valueOf(20));
alNumbers.add(String.valueOf(25));
For the following input :::
alNumbers.add(String.valueOf(10));
alNumbers.add(String.valueOf(15));
alNumbers.add(String.valueOf(20));
alNumbers.add(String.valueOf(25));
alNumbers.add(String.valueOf(110));
alNumbers.add(String.valueOf(130));
I am very new to Android and Java as well. So, if this is not a good solution, please don't mind.
Hope it helps...
You could probaly simplify your code using this idea:
static int ggt(int a, int b)
{
if (b == 0)
return a;
return ggt(b, a % b);
}
static void Main(string[] args)
{
int lcm = 1;
foreach(int x in new int[] { 1,5,7,9 })
lcm = x * lcm / ggt(x, lcm);
Console.WriteLine("{0}", lcm);
}
Syntax is c#, but hopefully readable enough. 'ggt' ist the german abbrevation for 'gcd' (greatest common divisor)
//LCM of range of numbers using JAVA
n=s.nextInt();//Reading range value
for(i=0;i<n;i++)
{
a[i]=s.nextInt(); //reading list of numbers
}
Arrays.sort(a,0,n); //Sorting the numbers
k=a[n-1]; //Assigning biggest value in the sorted array to k
j=1;
l=k;
for(i=0;i<n;i++)
{
if(k%a[i]==0)
{
continue; //checking whether all the elements are divisible by k
}
else
{
j=j+1;
k=l*j;//multiples of highest element i.e k in the sorted array
i=-1;//Assigning -1 to i, so as to check whether all the elements
//in the array are divisible by k or not from the beginning
}
}
System.out.println("LCM of range of numbers:"+k);
Input:
6
2 4 6 8 9 3
Output:
LCM of range of numbers:72

SQLite Android. Managing data

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/

How to jumble a word from EditText and apply the jumbled word into a TextView

I need to know how to jumble a word entered into EditText.
The jumbled word will show in another TextView in the same interface.
I have tried to do this but I get a force close error. This is what I have tried within the button:
wordE = (EditText)findViewById(R.id.entry);
jumble = (TextView) findViewById(R.id.jumble);
Button link5Btn = (Button)findViewById( R.id.selected );
link5Btn.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
jumbleMe(al);
}
Which calls the method:
private void jumbleMe( String word ){
al = wordE.getText().toString();
ArrayList<Character> al = new ArrayList<Character>();
for (int i = 0; i < wordE.length(); i++) {
al.add(word.charAt(i));
}
Collections.shuffle(al);
jumble.setText( al.toString() );
}
I would appreciate any help on this. Thanks
You made some mistakes.
Try changing the code to:
link5Btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
jumbleMe(wordE.getText().toString());
}
});
and
private void jumbleMe(String word) {
ArrayList<Character> al = new ArrayList<Character>();
for (int i = 0; i < wordE.length(); i++) {
al.add(word.charAt(i));
}
Collections.shuffle(al);
String result = "";
for (Character character : al) {
result += character;
}
jumble.setText(result);
}

Categories

Resources