SQLite Android. Managing data - android

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/

Related

android firebase retrieving data more than once

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.

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);

Lock SMS in android

i developing an application where i want to block SMS of some specific numbers.for this purpose i have one an Activity and Second is BroadcastReceiver class. in Activity i have a list where User will enter a number that he want to block. but i don't how will List number will be Access in BroadcastReceiver class to block it. i Access An ArrayAdapter in BroadcastReceiver class but it does not perform to block a call. Any one help me..thanks in advance..
SmsLock.java
public class SmsLock extends BroadcastReceiver {
final SmsManager sms = SmsManager.getDefault();
String phoneNumber;
String senderNum;
NumberListActivity ma = new NumberListActivity();
NumberListActivity num = new NumberListActivity();
String[] number = new String[] { "+923327765798", "+923219750751",
"+923445508726" };
#Override
public void onReceive(Context context, Intent intent) {
ArrayAdapter<String> adapter = ma.getArrayAdapter();
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
phoneNumber = currentMessage.getDisplayOriginatingAddress();
senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
}
for (int i = 0; i < adapter.getCount(); i++) {
if (senderNum.contains(adapter.getItem(i))) {
abortBroadcast();
}
}
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);
}
}
}
NumberListActivity.java
public class NumberListActivity extends Activity {
SharedPreferences preferences1;
SharedPreferences.Editor spEditor1;
int count1 = 0;
ListView numList1;
Button btnAdd1;
ArrayList<String> list1 = new ArrayList<String>();
ArrayAdapter<String> adapter1;
public static final String Place1 = "placeKey";
SmsLock brd = new SmsLock();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sms_list);
preferences1 = getSharedPreferences("Place1", Context.MODE_PRIVATE);
spEditor1 = preferences1.edit();
count1 = preferences1.getInt("count1", 0);
if (count1 > 0) {
for (int i = 0; i < count1; i++) {
list1.add(preferences1.getString("Value1[" + i + "]", ""));
}
}
final EditText edit = (EditText) findViewById(R.id.Item);
numList1 = (ListView) findViewById(R.id.Smslist);
btnAdd1 = (Button) findViewById(R.id.Add);
adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list1);
numList1.setAdapter(adapter1);
numList1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
/*
* list.remove(position); //preferences.edit().clear().commit();
* preferences.edit().remove("Value["+position+"]").commit();
* //count-=1; // adapter.remove(adapter.getItem(position));
*/
count1 = preferences1.getInt("count1", 0);
// if (count > 0) {
for (int i = position; i < count1; i++) {
// list.add();
if (i < count1)
spEditor1.putString(
"Value1[" + i + "]",
preferences1.getString("Value1[" + (i + 1)
+ "]", ""));
spEditor1.commit();
}
// }
list1.remove(position);
count1 -= 1;
spEditor1.putInt("count1", count1);
spEditor1.commit();
// preferences.edit().remove(position);
adapter1.notifyDataSetChanged();
}
});
btnAdd1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// EditText edit = (EditText) findViewById(R.id.txtItem);
spEditor1.putString("Value1[" + count1 + "]", edit.getText()
.toString());
spEditor1.commit();
list1.add(preferences1.getString("Value1[" + count1 + "]", ""));
count1 += 1;
spEditor1.putInt("count1", count1);
spEditor1.commit();
adapter1.notifyDataSetChanged();
}
});
}
public ArrayAdapter<String> getArrayAdapter() {
return adapter1;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent int1 = new Intent(NumberListActivity.this, Main.class);
startActivity(int1);
finish();
}
}
In your broadCast receiver, I assume you have successfully extracted the incoming SMS's phone number and the list of Numbers that are blocked. Then this code is iterating through the list of blocked numbers and entering the if-block, appropriately.
for (int i = 0; i < adapter.getCount(); i++) {
if (senderNum.contains(adapter.getItem(i))) {
abortBroadcast();
}
}
If you are sure above flow is working fine and still you are not able to block the SMS being received, then one following might be the cause:
Priotity: In your manifest file you set a priority for for your application to receive the SMS_RECEIVED intent. Suppose, that your app has a priority 10 and the OS's default SMS app has priority 20, then your app is getting a chance to respond to SMS_RECEIVED intent only after the defaul SMS app. This explains why the abortBroadcast() does not seem to work in above code.
I suggest you set the highest priority possible for your broadCastReceiver in the manifest, so that you get the first chance to handle SMS_RECEIVED intent.
From API 19 and above, there can be only one SMS application on a device. If there are 2 or more apps that have a permission to intercept SMS then user has to specify which one of the availaible applications should serve as the defult SMS app. Then the chosen default SMS app will only have the permission to respond to SMS_RECEIVED intent and other applications will not get a chance to receive SMS_RECEIVED intent.
So you also need to set your target SDK to 18 or below to use the SMS interception normally or you need to read some documentation if you want your app to be compatible with API 19.
In order to access the numbers from which sms you want to block first you need to store all the numbers either in your SQlite database or in preferences so that they can be accessed in broadcast receivers then use
abortBroadcast();
to prevent messages to go into inbox.

create cron in android app

I have a problem, I need to make a method run every so often, the problem is that all my methods need an Activity to start and do not know how I need to give that activity. Try to create a Service and work with a timer but the problem radico that. I leave my methods for you to see.
public void push(Activity activity,String codigoEvento){
SessionManager manager = new SessionManager();
folioEvento = manager.getValue(activity,"folioEvento");
nombreCliente = manager.getValue(activity,"nombreCliente");
if(!(folioEvento.equals("") || nombreCliente.equals(""))){
ConnectionInternet cn = new ConnectionInternet();
if(cn.isNetworkAvailable(activity)){
String ids = "";
bdTickets = new TicketsBaseDatos(activity, "Eventrid", null, 1);
SQLiteDatabase db = bdTickets.getWritableDatabase();
Cursor c = db.rawQuery("SELECT inscripcion_id FROM Inscripcion WHERE validado=1 and sincronizado = 1 and codigo_usuario =SI-1",null);
if (c.moveToFirst()) {
do {
ids += c.getString(0)+",";
ContentValues valores = new ContentValues();
valores.put("sincronizado","1");
String[] args = new String[]{c.getString(0), codigoEvento};
db.update("Inscripcion", valores, "inscripcion_id=? AND codigo_evento=?", args);
} while(c.moveToNext());
}
db.close();
c.close();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(Config.URL_BASE+nombreCliente+"/"+Config.URL_PUSH+folioEvento+"/"+ids);
try {
String status = json.getString("status");
if(status.equals("1")){
System.out.println("BIEN");
}
else{
System.out.println("MAL");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
There are no lines in your code that require an Activity. There are many lines that require a Context. An Activity is a Context. A Service is a Context. If you change your Activity activity parameter to Context context, it would appear that your code should work using a Service instead of an Activity.

Programmatically set R.ID

I downloaded a class from Catch The Cows, it is akin to a Google Map object or at least that is what I am using it for.
It parses an XML file which lists the areas of the screen that should be touchable, and then creates them with this method.
This is here for context, I have commented out some parts of code, and added my own to try and resolve my issue
private Area addShape( String shape, String name, String coords, String id) {
Log.v("IDS:", "id was "+id);
Area a = null;
String rid = id.replace("#+id/", "");
Log.v("IDS:", "rid was "+rid);
// Generate a new ID for the area.
int _id = 1;
View vi = findViewById(_id);
while (vi!=null) {
_id++;
vi = findViewById(_id);
}
//View.generateViewId(); //=0;
Log.v("IDS:", "After conversion final time "+_id);
/*
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
Log.v("IDS:", "After conversion "+_id);
}
catch (Exception e) {
_id = 0;
Log.e("Exception ",e.getMessage());
} finally {
Log.v("IDS:", "After conversion final time "+_id);
}
*/
if (_id != 0) {
if (shape.equalsIgnoreCase("rect")) {
String[] v = coords.split(",");
if (v.length == 4) {
a = new RectArea(_id, name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2]),
Float.parseFloat(v[3]));
}
}
if (shape.equalsIgnoreCase("circle")) {
String[] v = coords.split(",");
if (v.length == 3) {
a = new CircleArea(_id,name, Float.parseFloat(v[0]),
Float.parseFloat(v[1]),
Float.parseFloat(v[2])
);
}
}
if (shape.equalsIgnoreCase("poly")) {
a = new PolyArea(_id,name, coords);
}
if (a != null) {
addArea(a);
}
} else {
Log.v("Loading ID: ","_id was 0");
}
return a;
}
Unfortunately nothing was rendering on the screen, and this was because _id = 0. This should be changed with this bit of code:
try {
Class<R.id> res = R.id.class;
Field field = res.getField(rid); // eg. rid = area10
_id = field.getInt(null);
}
How ever I am not sure what it does to try and debug it, can anyone explain what this snippet is doing?
R is a Read-Only class. It is generate at compile time and You should not use reflection to modify its field. Also you should avoid reflection to access the fields values. You should use the official API.
The comment at the first row of the class is
/* AUTO-GENERATED FILE. DO NOT MODIFY. */

Categories

Resources