What's wrong with my code? "no such table: TaxiFile" [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
here is the DBHelper class
package com.example.taxirecordapp;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context c, String dbName, int dbVer) {
super(c, dbName, null, dbVer);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String driverSQL = "CREATE TABLE DriverFile (DriverNumber TEXT PRIMARY KEY NOT NULL, DriverFName TEXT, DriverLName TEXT, DriverDateHired TEXT, DriverContactNumber TEXT, DriverAddress TEXT)";
String taxiSQL = "CREATE TABLE TaxiFile (TaxiPlateNumber TEXT PRIMARY KEY NOT NULL, TaxiDriverNumber TEXT, TaxiRentDate TEXT, TaxiDriverBalance INTEGER)";
db.execSQL(taxiSQL);
db.execSQL(driverSQL);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
String driverSQL = "DROP TABLE IF EXISTS DriverFile";
String taxiSQL = "DROP TABLE IF EXISTS TaxiFile";
db.execSQL(taxiSQL);
db.execSQL(driverSQL);
onCreate(db);
}
}
the AddTaxi class
package com.example.taxirecordapp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddTaxi extends Activity {
EditText etPlateNumber, etDate, etBalance, etDriverNumber;
Button btnSave, btnBack;
SQLiteDatabase dbase;
int position;
int balance = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_taxi);
DBHelper helper = new DBHelper(getApplication(), "TaxiRecordAppDB", 1);
dbase = helper.getWritableDatabase();
etPlateNumber = (EditText) findViewById(R.id.etPlateNumber);
etDate = (EditText) findViewById(R.id.etDate);
etBalance = (EditText) findViewById(R.id.etBalance);
etDriverNumber = (EditText) findViewById(R.id.etDriverNumber);
btnSave = (Button) findViewById(R.id.btnSave);
btnBack = (Button) findViewById(R.id.btnBack);
Intent i = getIntent();
position = i.getIntExtra("position", position);
Cursor rsCursor;
String[] rsFields = { "DriverNumber", "DriverFName", "DriverLName",
"DriverDateHired", "DriverContactNumber", "DriverAddress" };
rsCursor = dbase.query("DriverFile", rsFields, null, null, null, null,
null, null);
rsCursor.moveToPosition(position);
if (rsCursor.isAfterLast() == false) {
if (rsCursor.getPosition() == position) {
etDriverNumber.setText(rsCursor.getString(0).toString());
}
}
rsCursor.close();
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (etPlateNumber.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Plate Number!", Toast.LENGTH_SHORT)
.show();
} else if (etDate.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Date Rented!", Toast.LENGTH_SHORT)
.show();
}
else {
if (etBalance.getText().toString().length() == 0) {
balance = 0;
} else {
balance = Integer.parseInt(etBalance.getText()
.toString());
}
AddTaxiRecord(etPlateNumber.getText().toString(),
etDriverNumber.getText().toString(), etDate
.getText().toString(), balance);
}
}
});
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AddTaxi.this, MainActivity.class);
startActivity(i);
}
});
}
public void AddTaxiRecord(String plateNumber, String driverNumber,
String date, int balance) {
try {
Cursor rsCursor;
String[] rsFields = { "TaxiPlateNumber", "TaxiDriverNumber",
"TaxiRentDate", "TaxiDriverBalance" };
rsCursor = dbase.query("TaxiFile", rsFields, "TaxiPlateNumber = "
+ plateNumber, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast() == false) {
Toast.makeText(getApplicationContext(),
"Plate number already exist!", Toast.LENGTH_SHORT)
.show();
} else {
ContentValues rsValues = new ContentValues();
rsValues.put("TaxiPlateNumber", plateNumber);
rsValues.put("TaxiDriverNumber", driverNumber);
rsValues.put("TaxiRentDate", date);
rsValues.put("TaxiDriverBalance", balance);
dbase.insert("TaxiFile", null, rsValues);
Toast.makeText(getApplicationContext(),
"Record Successfully Saved!", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
}
}
}
and the AddDriver class which is working fine
package com.example.taxirecordapp;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddDriver extends Activity {
EditText etDriverNumber, etFirstName, etLastName, etDateHired,
etContactNumber, etAddress;
Button btnSave, btnBack;
SQLiteDatabase dbase;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_driver);
etDriverNumber = (EditText) findViewById(R.id.etDriverNumber);
etFirstName = (EditText) findViewById(R.id.etFirstName);
etLastName = (EditText) findViewById(R.id.etLastName);
etDateHired = (EditText) findViewById(R.id.etDateHired);
etContactNumber = (EditText) findViewById(R.id.etContactNumber);
etAddress = (EditText) findViewById(R.id.etAddress);
btnSave = (Button) findViewById(R.id.btnSave);
btnBack = (Button) findViewById(R.id.btnBack);
DBHelper helper = new DBHelper(getApplication(), "TaxiRecordAppDB", 1);
dbase = helper.getWritableDatabase();
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (etDriverNumber.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver Number!", Toast.LENGTH_SHORT)
.show();
} else if (etFirstName.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's First Name!",
Toast.LENGTH_SHORT).show();
} else if (etLastName.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Last Name!",
Toast.LENGTH_SHORT).show();
} else if (etDateHired.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Date Hired!",
Toast.LENGTH_SHORT).show();
} else if (etContactNumber.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Contact Number!",
Toast.LENGTH_SHORT).show();
} else if (etAddress.getText().toString().length() == 0) {
Toast.makeText(getApplicationContext(),
"Please input Driver's Address!",
Toast.LENGTH_SHORT).show();
}
else {
AddDriverRecord(Integer.parseInt(etDriverNumber.getText()
.toString()), etFirstName.getText().toString(),
etLastName.getText().toString(), etDateHired
.getText().toString(), etContactNumber
.getText().toString(), etAddress.getText()
.toString());
}
}
});
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AddDriver.this,
MainActivity.class);
startActivity(i);
}
});
}
public void AddDriverRecord(int driverNumber, String firstName,
String lastName, String dateHired, String contactNumber,
String address) {
try {
Cursor rsCursor;
String[] rsFields = { "DriverNumber", "DriverFName", "DriverLName",
"DriverDateHired", "DriverContactNumber", "DriverAddress" };
rsCursor = dbase.query("DriverFile", rsFields, "DriverNumber = "
+ driverNumber, null, null, null, null, null);
rsCursor.moveToFirst();
if (rsCursor.isAfterLast() == false) {
Toast.makeText(getApplicationContext(),
"Driver number already exist!", Toast.LENGTH_SHORT)
.show();
} else {
ContentValues rsValues = new ContentValues();
rsValues.put("DriverNumber", driverNumber);
rsValues.put("DriverFName", firstName);
rsValues.put("DriverLName", lastName);
rsValues.put("DriverDateHired", dateHired);
rsValues.put("DriverContactNumber", contactNumber);
rsValues.put("DriverAddress", address);
dbase.insert("DriverFile", null, rsValues);
Toast.makeText(getApplicationContext(),
"Record Successfully Saved!", Toast.LENGTH_SHORT)
.show();
}
} catch (Exception e) {
}
}
}

I don't see any problems. So my guess is that you added the TaxiFile table after you added the DriverFile table.
To ensure that onUpgrade is called, you need to increase the database version but you are still using 1:
DBHelper helper = new DBHelper(getApplication(), "TaxiRecordAppDB", 1);
That probably means that TaxiFile is never created.
Every database schema change requires an increment of database version to make sure that onUpgrade is called.
Edit:
While development you can do the shortcut: Keep the version 1 but delete the app on the device or clear the data in the app info (both will force a complete new creation of the database).
Be warned: That shortcut does not work as soon as you have the app published because the user should never be required to do that. In that case you really need to handle schema changes and version increments by yourself.

Related

having issues with sip api support

i am creating sip application. i am testing it on my micromax a26 and it has android 2.3.5 and i am having problems
-->1
when i am executing this code
if(SipManager.isApiSupported(getApplicationContext()))
Toast.makeText(getApplicationContext(), "support", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "not support", Toast.LENGTH_SHORT).show();
i am getting "not support" alert.
in this http://developer.android.com/guide/topics/connectivity/sip.html it says i need You must have a mobile device that is running Android 2.3 or higher.
what i am missing???
-->2
at this line
if(manager == null) {
manager = SipManager.newInstance(this);
}
if (manager == null) {
Toast.makeText(getApplicationContext(), "manager null", Toast.LENGTH_SHORT).show();
return;
}
i am again getting alert "manager null" so i can guess that SipManager.newInstance(this) is retuning null. see this http://developer.android.com/reference/android/net/sip/SipManager.html#newInstance%28android.content.Context%29
this is my whole code
package com.archish;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.*;
import android.net.sip.*;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.text.ParseException;
public class SipTestActivity extends Activity implements View.OnTouchListener{
public String sipAddress;
public static SipManager manager = null;
public SipProfile me = null;
public SipAudioCall call =null;
//public IncomingCallReceiver callReceiver;
EditText Domain;
EditText UId;
EditText Pwd;
private static final int CALL_ADDRESS = 1;
private static final int SET_AUTH_INFO = 2;
private static final int UPDATE_SETTINGS_DIALOG = 3;
private static final int HANG_UP = 4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Domain=(EditText)findViewById(R.id.edtDomain);
UId=(EditText)findViewById(R.id.edtUid);
Pwd=(EditText)findViewById(R.id.edtPwd);
if(SipManager.isApiSupported(getApplicationContext()))
Toast.makeText(getApplicationContext(), "support", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(), "not support", Toast.LENGTH_SHORT).show();
IntentFilter filter = new IntentFilter();
filter.addAction("com.archish.INCOMING_CALL");
initializeManager();
/*Button Reg=(Button)findViewById(R.id.btnReg);
Reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "on click ", Toast.LENGTH_SHORT).show();
try {
Register();
} catch (SipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});*/
}
private void initializeManager() {
if(manager == null) {
manager = SipManager.newInstance(getBaseContext());
}
Register();
}
public void Register()
{
if (manager == null) {
Toast.makeText(getApplicationContext(), "manager null", Toast.LENGTH_SHORT).show();
return;
}
if (me != null) {
closeLocalProfile();
}
try{
SipProfile.Builder builder = new SipProfile.Builder("1001", "123");
builder.setPassword("1234");
me = builder.build();
Intent i = new Intent();
i.setAction("com.archish.INCOMING_CALL");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, Intent.FILL_IN_DATA);
manager.open(me, pi, null);
// This listener must be added AFTER manager.open is called,
// Otherwise the methods aren't guaranteed to fire.
manager.setRegistrationListener(me.getUriString(), new SipRegistrationListener() {
public void onRegistering(String localProfileUri) {
Toast.makeText(getApplicationContext(), "Registering with SIP Server...", Toast.LENGTH_SHORT).show();
// updateStatus("Registering with SIP Server...");
}
public void onRegistrationDone(String localProfileUri, long expiryTime) {
Toast.makeText(getApplicationContext(), "reaDy", Toast.LENGTH_SHORT).show();
// updateStatus("Ready");
}
public void onRegistrationFailed(String localProfileUri, int errorCode,
String errorMessage) {
Toast.makeText(getApplicationContext(), "Registration failed. Please check settings.", Toast.LENGTH_SHORT).show();
// updateStatus("Registration failed. Please check settings.");
}
});
}
catch (ParseException pe) {
//updateStatus("Connection Error.");
} catch (SipException se) {
//updateStatus("Connection error.");
}
}
private void closeLocalProfile() {
if (manager == null) {
return;
}
try {
if (me != null) {
manager.close(me.getUriString());
}
} catch (Exception ee) {
Log.d("WalkieTalkieActivity/onDestroy", "Failed to close local profile.", ee);
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
please help me !!! i am new in android, give me any hint to solve this... what is the problem????

Contact chooser returning null value

I am trying to implement contact pciker in android, i am able to launch contact picker in android, but when i select the contact i get back null value, i.e. no number in my textfield. What am i doing wrong ?
Here is my code.
mainactivity.java
package com.example.textmessage;
import java.util.Timer;
import java.util.TimerTask;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.Settings;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentActivity;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import com.google.android.gms.maps.SupportMapFragment;
import android.widget.Toast;
public class MainActivity extends FragmentActivity{
protected static final int CONTACT_PICKER_RESULT = 0;
int count=0;
private RadioButton radioBtnten;
private RadioButton radioBtnone;
Button sendBtn,contact;
EditText txtphoneNo;
EditText txtMessage;
GPSTracker gps;
Timer timer;
TimerTask timerTask;
final Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
radioBtnten=(RadioButton)findViewById(R.id.ten);
radioBtnone=(RadioButton)findViewById(R.id.one);
sendBtn = (Button) findViewById(R.id.btnSendSMS);
txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
contact = (Button)findViewById(R.id.contact);
//txtMessage //= (EditText) findViewById(R.id.editTextSMS);
gps = new GPSTracker(MainActivity.this);
contact.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
// c.moveToFirst();
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
txtphoneNo.setText(phone);
}
}
}
sendBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
startTimer();
sendSMSMessage();
Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
startActivityForResult(toAnotherActivity, 0);
}
});
}
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
if(radioBtnten.isChecked()==true)
timer.schedule(timerTask, 5000, 10000);
// if(radioBtn2.isSelected()==true)
else if(radioBtnone.isChecked()==true)
timer.schedule(timerTask, 5000, 1000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
//get the current timeStamp
Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
sendSMSMessage();
//show the toast
}
});
}
};
}
public void stoptimertask(View v)
{
//stop the timer, if it's not already null
Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
if (timer != null)
{
timer.cancel();
timer = null;
}
}
protected void sendSMSMessage() {
Log.i("Send SMS", "");
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
String phoneNo = txtphoneNo.getText().toString();
String message = "These are my co-ordinates:-"+ latitude + ", " + longitude;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
P.S. i have mentioned the permission in manifest.
From your code it seems to be you have not added onActivityResult method. Put the following code in in onActivityResult method
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
Uri contact = data.getData();
ContentResolver cr = getContentResolver();
Cursor c = managedQuery(contact, null, null, null, null);
while(c.moveToNext()){
String id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?", new String[]{id}, null);
while(pCur.moveToNext()){
String phone = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
tv.setText( phone);
}
}
}}

how to change a static variable in broadcaster onReceive

I want to get the sending status of each phone number, so I define a variable statusMap to record the status, 0 means success, 1 means failed. And I assign value to statusMap at onReceive function, but after that the statusMap's value is still empty. how can I change a static value in onReceive function
package com.mem.memsms;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class SendMessage extends Activity {
private EditText editText;
private Button button;
private Intent intent;
private SendBroadcast mSendReceiver;
private HashMap<String, String> hashMap;
private HashMap<String, String> statusMap = new HashMap<String, String>();
private Queue<String> numbers;
String SENT_SMS_ACTION = "SENT_SMS_ACTION";
String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
#SuppressWarnings("unchecked")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
editText = (EditText) this.findViewById(R.id.message);
intent = getIntent();
hashMap = (HashMap<String, String>) intent.getSerializableExtra("data");
numbers = new LinkedList<String>();
button = (Button) this.findViewById(R.id.sendmessage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
numbers.clear();
editText.setEnabled(false);
final String text = editText.getText().toString();
if (text.trim() == "") {
editText.setHint(R.string.msg_null);
return;
}
Iterator<Entry<String, String>> iter = hashMap.entrySet()
.iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter
.next();
String number = entry.getKey();
String content = entry.getValue();
numbers.offer(number);
Sendmsg(number, content + text);
}
intent.putExtra("data2", statusMap);
setResult(RESULT_OK, intent);
//Log.i("msg", "statusMap length is" + statusMap.size());
// back to contacts
SendMessage.this.finish();
}
});
}
private class SendBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String n = numbers.poll();
switch (getResultCode()) {
case RESULT_OK:
Log.i("msg", "c:ok" + n);
statusMap.put(n, "0");
break;
default:
Log.i("msg", "c:failed" + n);
statusMap.put(n, "1");
break;
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
this.unregisterReceiver(mSendReceiver);
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
mSendReceiver = new SendBroadcast();
IntentFilter mSendFilter = new IntentFilter(SENT_SMS_ACTION);
this.registerReceiver(mSendReceiver, mSendFilter);
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.send_message, menu);
return true;
}
private void Sendmsg(String number, String content) {
Intent sentIntent = new Intent(SENT_SMS_ACTION);
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, sentIntent,
0);
//sentIntent.putExtra("status", statusMap);
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(number, null, content, sentPI, null);
}
}
Remove this:
intent.putExtra("data2", statusMap);
setResult(RESULT_OK, intent);
//Log.i("msg", "statusMap length is" + statusMap.size());
// back to contacts
SendMessage.this.finish();
code from onClick and put it in onReceive:
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String n = numbers.poll();
switch (getResultCode()) {
case RESULT_OK:
Log.i("msg", "c:ok" + n);
statusMap.put(n, "0");
break;
default:
Log.i("msg", "c:failed" + n);
statusMap.put(n, "1");
break;
}
if(hashMap.size()==statusMap.size()){
intent.putExtra("data2", statusMap);
SendMessage.this.setResult(RESULT_OK, intent);
//Log.i("msg", "statusMap length is" + statusMap.size());
// back to contacts
SendMessage.this.finish();
}
}
The problem was that the onClick event is completed first that is you call set result and finish this activity and then onReceive is getting called so by the time your map is updated result was already sent

Fetching image from SQLite database in android

I am unable to fetch the image from the database, please look at my databasehelper (that is my fetchimg(String i) and MainActivity (that is showmeth(View w)) class.
What I am actually doing here is firstly capturing the image with camera, then it is temporary pasted on 1st ImageView and after i click on save button it gets saved in the database(No problem yet). But when i click show button then it must show the image in a 2nd ImageView by taking reference id as a textview's id but it is not showing the image, that is showmeth(View w) unable to fetch the image from database.
My MainActivity
package com.example.expnewbutton;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Uri fileUri;
Bitmap img;
TextView t1;
databasehelper helper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1 = (TextView) findViewById(R.id.text);
helper = new databasehelper(this);
}
public void cammethod(View w) {
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
// fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.", Toast.LENGTH_LONG)
.show();
}
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
} else {
// The picture was returned
Bundle extras = intent.getExtras();
img = (Bitmap) extras.get("data");
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
public void insertimg(View w) {
long a = 0;
String id = t1.getText().toString();
try {
helper.deleterecord(id);
a = helper.insert(id, img);
if (a >= 1) {
Toast.makeText(getBaseContext(),
a + "Record Successfully Saved", 30).show();
} else {
Toast.makeText(getBaseContext(), "Not Saved", 30).show();
}
} catch (Exception e) {
Toast.makeText(getBaseContext(), "there is error", 5).show();
}
}
public void showmeth(View w) {
String i = null;
boolean flag = false;
i = t1.getText().toString();
try {
flag = helper.fetchimg(i);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "database exception", 10).show();
}
if (flag == true) {
Toast.makeText(getBaseContext(),
"Here your image save on imageview", 10).show();
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
imageView2.setImageBitmap(helper.bmp);
} else {
Toast.makeText(getBaseContext(), "Add a Pic first", 50).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
My Database File:
package com.example.expnewbutton;
import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;
public class databasehelper extends SQLiteOpenHelper {
final static String databasename = "Image";
final static int databaseversion = 1;
Bitmap bmp = null;
public databasehelper(Context ctx) {
super(ctx, databasename, null, databaseversion);
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
Log.d("tag4545", "database");
db.execSQL("create table mypic(id text,pic BLOB)");
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if Exists mypic");
// db.execSQL("drop table if Exists emer");
onCreate(db);
}
public long insert(String id, Bitmap img) {
SQLiteDatabase base = getWritableDatabase();
byte[] data = getBitmapAsByteArray(img); // this is a function
ContentValues value = new ContentValues();
value.put("id", id);
value.put("pic", data);
long a = base.insert("mypic", null, value);
return a;
}
public static byte[] getBitmapAsByteArray(Bitmap bitmap) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
public boolean fetchimg(String i) {
SQLiteDatabase base = getReadableDatabase();
Cursor cs = null;
try {
cs = base.query("mypic", new String[] { "pic" }, "id=?",
new String[] { "i" }, null, null, null);
/*
* String qu= "select pic from mypic where id"+i;
*
* Cursor cs=null; try{ cs =base.rawQuery(qu, null); }
* catch(Exception e) { return false; }
*/
if (cs != null) {
cs.moveToFirst();
byte[] imgbyte = cs.getBlob(0);
cs.close();
bmp = BitmapFactory.decodeByteArray(imgbyte, 0, imgbyte.length);
return true;
}
else {
return false;
}
}
catch (Exception e) {
return false;
}
}
public void deleterecord(String pe_id) {
SQLiteDatabase base = getWritableDatabase();
base.delete("mypic", "id=?", new String[] { pe_id });
}
}
My xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gb2"
tools:context=".MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_toRightOf="#+id/textView2"
android:onClick="cammethod"
android:text="Cam" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button1"
android:layout_marginLeft="46dp"
android:layout_toRightOf="#+id/button1"
android:onClick="insertimg"
android:text="Save" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button2"
android:layout_alignParentRight="true"
android:layout_marginRight="22dp"
android:text="Photo"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/text"
android:layout_toRightOf="#id/imageView1"
android:onClick="showmeth"
android:text="show" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/imageView1" />
</RelativeLayout>
Please help me in code, I need it soon. Thank you.
So the problem may be with database query(I tried query with both methods which i hidden or which is not hidden) or may be with using BLOB in my code. Please help me to find error
You are passing the string "i" where you need to pass the value of i.
You should change your query to:
cs = base.query("mypic", new String[] { "pic" }, "id=?",
new String[] { String.valueOf(i) }, null, null, null);

Not Bound To TTS Engine

I'm trying to make speaking dictionary.
LogCat shows "Successfully bound to com.android.tts" but when the Speak button clicked, it shows "failed speak : not bound to tts engine".
But on AVD it runs smoothly, why?
This Is my goTranslator class:
package sk.team;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import android.content.Intent;
import android.content.res.Configuration;
import java.util.Locale;
public class goTranslator extends Activity implements TextToSpeech.OnInitListener{
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
private SQLiteDatabase db = null;
private Cursor translatorCursor = null;
private EditText txtSearch;
private EditText txtResult;
private AppDatabase dbtranslator = null;
private RadioButton Eng,Ind;
private Button Translate,Speak;
public static final String ENGLISH = "english";
public static final String INDONESIA = "indonesia";
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
Toast.makeText(goTranslator.this,
"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(goTranslator.this,
"Error occurred while initializing Text-To-Speech engine",
Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
tts = new TextToSpeech(this, this);
} else {
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dbtranslator = new AppDatabase(this);
db = dbtranslator.getWritableDatabase();
setContentView(R.layout.main);
dbtranslator.createTable(db);
dbtranslator.generateData(db);
Eng = (RadioButton) findViewById(R.id.Eng);
Ind = (RadioButton) findViewById(R.id.Ind);
Translate = (Button) findViewById(R.id.Translate);
Speak = (Button) findViewById(R.id.Speak);
txtSearch = (EditText) findViewById(R.id.txtSearch);
txtResult = (EditText) findViewById(R.id.txtResult);
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
Speak.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text = txtResult.getText().toString();
if (text!=null && text.length()>0) {
Toast.makeText(goTranslator.this, "Saying: " + text,
Toast.LENGTH_LONG).show();
tts.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
});
}
public void Translate (View view) {
if (view == Translate) {
if (Eng.isChecked()) {
txtSearch.setHint("Masukkan Kata");
Locale loc = new Locale ("es_ES");
tts.setLanguage(loc);
String result = "";
String englishword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where ENGLISH='" + englishword
+ "' ORDER BY ENGLISH", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(2);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(2);
}
}
if (result.equals("")) {
result = "Kata Tidak Tersedia";
}
txtResult.setText(result);
}
if (Ind.isChecked()) {
txtSearch.setHint("Enter Word");
Locale loc = new Locale ("en_US");
tts.setLanguage(loc);
String result = "";
String indonesiaword = txtSearch.getText().toString().trim().toLowerCase();
translatorCursor = db.rawQuery("SELECT ID, ENGLISH, INDONESIA "
+ "FROM translator where INDONESIA='" + indonesiaword
+ "' ORDER BY INDONESIA", null);
if (translatorCursor.moveToFirst()) {
result = translatorCursor.getString(1);
for (; !translatorCursor.isAfterLast(); translatorCursor.moveToNext()) {
result = translatorCursor.getString(1);
}
}
if (result.equals("")) {
result = "Result Not Found";
}
txtResult.setText(result);
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.main);
}
#Override
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
if (translatorCursor != null) {
translatorCursor.close();
db.close();
}
}
}
Log.w(TAG, method + " failed: not bound to TTS engine");
I caused by
mServiceConnection;
Being null
Does your testing device lack an internet connection?

Categories

Resources