view content of database in textfield - java

below is the code which i made to insert an integer value into database. this code is to help the user to keep track of his/her account balance. in this code the content of the database is displayed as a toast message on button click. i want the content to be displayed in a text field when this activity is called. the textfield to display the content and the update button are on the same activity. so when the user enters the value to be added or subtracted from the database and when the update button is pressed the textfield should be refreshed with the updated value. plz make the sufficient changes in the code.
thank you
Main Activity.java
package com.sqltut;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save,load,deposit,withdraw;
EditText balance,updatevalue;
DataHandler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save=(Button) findViewById(R.id.save);
load=(Button) findViewById(R.id.load);
deposit=(Button) findViewById(R.id.deposit);
withdraw=(Button) findViewById(R.id.withdraw);
balance=(EditText) findViewById(R.id.balance);
updatevalue=(EditText) findViewById(R.id.updatevalue);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getbalance=balance.getText().toString();
int bal=Integer.parseInt(getbalance);
handler=new DataHandler(getBaseContext());
handler.open();
long id=handler.insertData(bal);
Toast.makeText(getBaseContext(), "Data Inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int getbalance;
getbalance=0;
handler=new DataHandler(getBaseContext());
handler.open();
Cursor C=handler.returnData();
if(C.moveToFirst())
{
do
{
getbalance=C.getInt(0);
}while(C.moveToNext());
}
handler.close();
Toast.makeText(getBaseContext(), "Balance:"+getbalance,Toast.LENGTH_LONG).show();
}
});
withdraw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String updt=updatevalue.getText().toString();
int value=Integer.parseInt(updt);
int flag=0;
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(value,flag);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
handler.close();
}
});
deposit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String updt=updatevalue.getText().toString();
int value=Integer.parseInt(updt);
int flag=1;
handler=new DataHandler(getBaseContext());
handler.open();
handler.updateData(value,flag);
Toast.makeText(getBaseContext(), "Data Updated", Toast.LENGTH_LONG).show();
handler.close();
}
});
//to call next activity
Button createAppointment = (Button)findViewById(R.id.Next);
createAppointment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(MainActivity.this, Page2.class);
MainActivity.this.startActivity(myIntent);
}
});
}
#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;
}
}
DataHandler.java
package com.sqltut;
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;
public class DataHandler {
public static final String BALANCE="balance";
public static final String TABLE_NAME="mytable";
public static final String DATA_BASE_NAME="mydatabase";
public static final int DATABASE_VERSION=1;
public static final String TABLE_CREATE="create table mytable(balance integer not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx)
{
this.ctx = ctx;
dbhelper=new DataBaseHelper(ctx);
}
private static class DataBaseHelper extends SQLiteOpenHelper
{
public DataBaseHelper(Context ctx)
{
super(ctx,DATA_BASE_NAME,null,DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
try{
db.execSQL(TABLE_CREATE);
}
catch(SQLException e)
{
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS mytable ");
onCreate(db);
}
}
public DataHandler open()
{
db=dbhelper.getWritableDatabase();
return this;
}
public void close()
{
dbhelper.close();
}
public long insertData(Integer balance)
{
ContentValues content=new ContentValues();
content.put(BALANCE, balance);
return db.insert(TABLE_NAME, null, content);
}
public void updateData(Integer value,Integer flag)
{
db = dbhelper.getReadableDatabase();
String selectQuery = "select balance from " + TABLE_NAME ;
Cursor cursor = db.rawQuery(selectQuery, null);
int current = 0;
if (cursor.moveToFirst()) {
current= Integer.parseInt(cursor.getString(0));
}
if(flag==0){
current = current-value;
}else {
current = current+value ;
}
cursor.close();
db.close();
try{
db = dbhelper.getWritableDatabase();
String rawQuery = "update mytable set balance="+current;
db.execSQL(rawQuery);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public Cursor returnData()
{
return db.query(TABLE_NAME, new String[] {BALANCE}, null, null, null, null, null);
}
}

write a method in database like this.
public int getValue(){
//get present value from your crud operations
//you have to relate with CRUD values and get the int value
//call the method to get you required value, ex; If delete operation is done then you have give updated value to this method or insert is done then you have to call this method and you have to send the updated value to this, similarly you have to do this for update operation also. then you will get the value into this method whether any operation has done on database.
}
step1:call the method from you button click.
step2:inside getValue() invoke each crud method to get updated value.
try in this way.
call the method in the onClick of Button.
hope this may helps you

Related

Sqlite Error On Android Application

Im trying to build an app that sets many alarm clocks and i want to save the alarms with an SQLite database. Already watched many tutorials for this but still having a problem using the database. Firstly i want to save the alarm one by one by pushing a button. I tried also to insert manually 2 alarms but it didnt worked either. What am i doing wrong? I am pretty new to this!
DBHelper Class
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String ALARMS_TABLE_NAME = "alarms";
public static final String ALARMS_COLUMN_ID = "id";
public static final String ALARMS_COLUMN_HOUR = "hour";
public static final String ALARMS_COLUMN_MINUTES = "minutes";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, 33);
}
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE "+ALARMS_TABLE_NAME+" ("+ALARMS_COLUMN_ID+ " INTEGER PRIMARY KEY , "+
ALARMS_COLUMN_HOUR+ " INTEGER, "+ALARMS_COLUMN_MINUTES+" INTEGER)");
InsertAlarms(db);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS "+ALARMS_TABLE_NAME);
onCreate(db);
}
void AddAlarm(Alarm alarm)
{
SQLiteDatabase db= this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_HOUR, alarm.getHour());
cv.put(ALARMS_COLUMN_MINUTES, alarm.getMinutes());
db.insert(ALARMS_TABLE_NAME, null, cv);
db.close();
}
Cursor getAllAlarms()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("SELECT * FROM "+ALARMS_TABLE_NAME,null);
return cur;
}
void InsertAlarms(SQLiteDatabase db) //insert manually 2 alarms
{
ContentValues cv=new ContentValues();
cv.put(ALARMS_COLUMN_ID, 1);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
cv.put(ALARMS_COLUMN_ID, 2);
cv.put(ALARMS_COLUMN_HOUR, 20);
cv.put(ALARMS_COLUMN_MINUTES, 20);
db.insert(ALARMS_TABLE_NAME, null, cv);
}
int getAlarmCount()
{
SQLiteDatabase db=this.getWritableDatabase();
Cursor cur= db.rawQuery("Select * from "+ALARMS_TABLE_NAME, null);
int x= cur.getCount();
cur.close();
return x;
}
Class Alarm:
public class Alarm {
int _id;
int _hour;
int _minutes;
public Alarm(int Hour, int Minutes)
{
this._hour=Hour;
this._minutes=Minutes;
}
public int getID()
{
return this._id;
}
public void SetID(int ID)
{
this._id=ID;
}
public int getHour()
{
return this._hour;
}
public int getMinutes()
{
return this._minutes;
}
public void setHour(int Hour)
{
this._hour=Hour;
}
public void setMinutes(int Minutes)
{
this._minutes=Minutes;
}
Activity AddAlarm
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour=(EditText)findViewById(R.id.txtHour);
txtMinutes=(EditText)findViewById(R.id.txtMinutes);
Button button1 = (Button)findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view)
{
boolean ok=true;
try
{
int hour=Integer.parseInt(txtHour.getText().toString());
int minutes=Integer.parseInt(txtMinutes.getText().toString());
Alarm al=new Alarm(hour,minutes);
Toast.makeText(AddAlarm.this,"ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
}
catch(Exception ex)
{
Toast.makeText(AddAlarm.this,"ERROR! ", Toast.LENGTH_LONG).show();
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
Intent intent=getIntent();
DBHelper mydb;
TextView xupnitiria;
String hour;
public static boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.set_alarm_button);
//Bundle extras=intent.getExtras();
mydb=new DBHelper(this);
xupnitiria =(TextView)findViewById(R.id.xupnitiria);
xupnitiria.setText(xupnitiria.getText()+String.valueOf(mydb.getAlarmCount()));
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
Intent a= new Intent(MainActivity.this, AddAlarm.class);
startActivity(a);
}
});
}
Errors on android Monitor
10-04 15:07:26.592 2625-2625/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection csk#8709fba that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1336)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1231)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1450)
at android.app.ContextImpl.bindService(ContextImpl.java:1422)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms:0)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms:1)
at bvq.run(:com.google.android.gms:9)
at bvn.run(:com.google.android.gms:10)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Add following in onCreate() of AddAlarm.java:
dbHelper=new DBHelper(this);
Also to see error log in logcat add following in try-catch block:
ex.printStackTrace();
AddAlarm Activity:
public class AddAlarm extends Activity {
EditText txtHour;
EditText txtMinutes;
DBHelper dbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addalarm);
txtHour = (EditText) findViewById(R.id.txtHour);
txtMinutes = (EditText) findViewById(R.id.txtMinutes);
dbHelper=new DBHelper(this);
Button button1 = (Button) findViewById(R.id.addalarmbtn);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
btnAddAlarm_Click(v);
}
});
}
public void btnAddAlarm_Click(View view) {
boolean ok = true;
try {
int hour = Integer.parseInt(txtHour.getText().toString());
int minutes = Integer.parseInt(txtMinutes.getText().toString());
Alarm al = new Alarm(hour, minutes);
Toast.makeText(AddAlarm.this, "ADDED! ", Toast.LENGTH_LONG).show();
dbHelper.AddAlarm(al);
} catch (Exception ex) {
Toast.makeText(AddAlarm.this, "ERROR! ", Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
}

Pass callback method result with in a non-activity class to android activity class?

I need to create twitter fabric re-usable component.my first step to allow login with twitter by simply calling method from a class.
Code
CLASS
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterAuthClient;
import com.twitter.sdk.android.core.models.Tweet;
import com.twitter.sdk.android.core.services.StatusesService;
import io.fabric.sdk.android.Fabric;
public class TwitterAuth {
private String CONSUMER_KEY;
private String CONSUMER_SECRET;
private Context context;
private TwitterAuthClient client;
private StatusesService service;
public TwitterAuth(Context context, String CONSUMER_KEY, String CONSUMER_SECRET) {
this.CONSUMER_KEY = CONSUMER_KEY;
this.CONSUMER_SECRET = CONSUMER_SECRET;
this.context = context;
configureKey();
}
public void configureKey() {
TwitterAuthConfig authConfig = new TwitterAuthConfig(CONSUMER_KEY, CONSUMER_SECRET);
Fabric.with(context, new Twitter(authConfig));
}
public void doLogin() {
client = new TwitterAuthClient();
client.authorize((Activity) context, new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> twitterSessionResult) {
final TwitterSession session = Twitter.getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
String userName = session.getUserName();
Toast.makeText(context, "TWITTER EASY LIB TEST :: Done Login With \n Username :" + userName + " \n Token :" + token + "\n Secret :" + secret, Toast.LENGTH_LONG).show();
//Toast.makeText(MainActivity.this, "success", Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "TWITTER EASY LIB TEST :: failure", Toast.LENGTH_SHORT).show();
}
});
}
public void doLogout() {
Twitter.getSessionManager().clearActiveSession();
}
public void publishTweet(String tweet) {
service = Twitter.getInstance().getApiClient().getStatusesService();
service.update(tweet, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(context, "Tweet Updated !",
Toast.LENGTH_SHORT).show();
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "Error occured !",
Toast.LENGTH_SHORT).show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
client.onActivityResult(requestCode, resultCode, data);
}
}
Activity
package codelynks.twitter.twitterintegration;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import com.easytweet.TwitterAuth;
public class CheckLib extends ActionBarActivity {
private Button cus;
private TwitterAuth auth;
private String CONSUMER_KEY = "", CONSUMER_SECRET = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = new TwitterAuth(CheckLib.this, CONSUMER_KEY, CONSUMER_SECRET);
setContentView(R.layout.activity_main);
cus = (Button) findViewById(R.id.cusbutton);
cus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth.doLogin();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
auth.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Here i will get the result on callback method
public void success(Result<TwitterSession> twitterSessionResult) {}
**or**
public void failure(TwitterException e) {}
How can i pass this result(SUCCESS/FAILURE) to activity CheckLib for doing further actions.?
any help would be appreciated :)
you can set listener for success or failure in your TwitterAuth.class and then set this listener in your activity (CheckLib.class) to notify you when success or failure, like this:
public class TwitterAuth {
private TwitterLoginListener listener;
public void setListener( TwitterLoginListener listener){
this.listener = listener;
}
Interfase TwitterLoginListener{
public void success(Result<TwitterSession> twitterSessionResult);
public void failure(TwitterException e);
}
.
.
.
in success and failure method you need to fill listener:
in success method (in TwitterAuth.class):
if(listener != null){
listener.success(twitterSessionResult);
}
in failure method (in TwitterAuth.class):
if(listener != null){
listener.failure(e);
}
then in your activity set listener:
.
.
.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = new TwitterAuth(CheckLib.this, CONSUMER_KEY, CONSUMER_SECRET);
auth.setListener(new TwitterLoginListener{
#Override
public void success(Result<TwitterSession> twitterSessionResult){
//login success
}
#Override
public void failure(TwitterException e){
//login failed
}
});
.
.
.
If it is a primitive type, like a boolean or a String (ok, this one is not primitive, but still), you can pass it as an Extra in an Intent which you send to the activity.
If it is a more complex object or you do not have Context access in your class, try greenrobot EventBus, a pretty cool library created exactly for such situations.
You can use interface and implement the interface method from your dologin method
check my sample
public interface sampleInterface {
// you can define any parameter as per your requirement
public void yourMethod(boolean value);
}
public void doLogin(sampleInterface si) {
public void publishTweet(String tweet) {
sampleInterface sampleIn;
service = Twitter.getInstance().getApiClient().getStatusesService();
service.update(tweet, null, null, null, null, null, null, null, new Callback<Tweet>() {
#Override
public void success(Result<Tweet> tweetResult) {
Toast.makeText(context, "Tweet Updated !",
Toast.LENGTH_SHORT).show();
si.yourMethod(true);
}
#Override
public void failure(TwitterException e) {
Toast.makeText(context, "Error occured !",
Toast.LENGTH_SHORT).show();
si.yourMethod(false);
}
});
}
}
inside your activity class
public void onClick(View v) {
auth.doLogin(new sampleInterface() {
#Override
public void yourMethod(boolean value) {
//GET your result
}
});
}

how to set all fields to mandatory fields in android app having two edittexts and one spinner

package com.example.dentalproject;
import android.app.Activity;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
/** Called when the activity is first created. */
EditText ettokenno,etcomments;
Button btnfeedback;
Spinner ratingspinner;
DatabaseAdapter dbAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter=new DatabaseAdapter(getApplicationContext());
ettokenno=(EditText)findViewById(R.id.ed_tokennum);
etcomments=(EditText)findViewById(R.id.ed_yourcomments);
ratingspinner = (Spinner)findViewById(R.id.sp1_select);
btnfeedback=(Button)findViewById(R.id.btnfeedback);
btnfeedback.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btnfeedback)
//if(ettokenno.equals("")&&(etcomments.equals("")))
{
//Toast.makeText(getApplicationContext(), "save",Toast.LENGTH_LONG).show();
String Tokenno=ettokenno.getText().toString();
String Comments=etcomments.getText().toString();
String Rating = ratingspinner.getSelectedItem().toString();
//String Rating = "Good";
if(Tokenno.equals(""))
{
Toast.makeText(getApplicationContext(), "please enter value",Toast.LENGTH_LONG).show();
}
if(Comments.equals(""))
{
Toast.makeText(getApplicationContext(), "please enter value",Toast.LENGTH_LONG).show();
}
dbAdapter.open();
long inserted=dbAdapter.insertTest(Tokenno,Comments, Rating);
if(inserted >0)
{
Toast.makeText(getApplicationContext(), "data saved",Toast.LENGTH_LONG).show();
ettokenno.setText("");
etcomments.setText("");
}
else
{
Toast.makeText(getApplicationContext(), "data not saved",Toast.LENGTH_LONG).show();
}
dbAdapter.close();
}
in this app i am having two edittexts and one spinner , how to restrict user to fill all fields and how to generate dialogue box when user leave the edit text and spinner with out filling data, please help me friends thanks in advance
}
}
This is for two TextView's
if (!text1.getText().toString().isEmpty() && !text2.getText().toString().isEmpty()){
// Your Dialog or Toast for warning
}
else{
// your further code
}
and for Spinner you can set setOnItemSelectedListener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
spinner.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
spinner.setSelection(0);
}
});
Use a boolean variable, say, flag
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btnfeedback)
//if(ettokenno.equals("")&&(etcomments.equals("")))
{
//Toast.makeText(getApplicationContext(), "save",Toast.LENGTH_LONG).show();
String Tokenno=ettokenno.getText().toString();
String Comments=etcomments.getText().toString();
String Rating = ratingspinner.getSelectedItem().toString();
boolean flag = true;
if(Tokenno.equals(""))
{
Toast.makeText(getApplicationContext(), "please enter value",Toast.LENGTH_LONG).show();
flag = false;
}
if(Comments.equals(""))
{
Toast.makeText(getApplicationContext(), "please enter value",Toast.LENGTH_LONG).show();
flag = false;
}
if(flag) {
dbAdapter.open();
long inserted=dbAdapter.insertTest(Tokenno,Comments, Rating);
if(inserted >0)
{
Toast.makeText(getApplicationContext(), "data saved",Toast.LENGTH_LONG).show();
ettokenno.setText("");
etcomments.setText("");
}
else
{
Toast.makeText(getApplicationContext(), "data not saved",Toast.LENGTH_LONG).show();
}
}
dbAdapter.close();
}
Try following code in your onClick
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.btnfeedback)
{
String Tokenno=ettokenno.getText().toString().trim();
if(TextUtils.isEmpty(Tokenno)){
//show dialog for Tokenno
return;
}
String Comments=etcomments.getText().toString();
if(TextUtils.isEmpty(Comments)){
//show dialog for Comments
return;
}
String Rating = ratingspinner.getSelectedItem().toString();
if(Rating.equals("YOUR_DEFAULT_VALUE")){
//show dialog for rating
return;
}
//all fields are filled
}
Here is Tutorial to display different types of dialogs

Restrict speech Recognition to Alpha-numeric words

I want to use the Speech Recongnition to handle commands in my application. I know
at any given point in my application what the valid commands would be
at that point so would like to limit the results that the Speech Recongnition is
matched against.
I mean in my app .. The valid words are only numbers plus alphabets. I mean number like A13FG6 something like that.
I would
like to be able to restrict the Speech recongnition to only try and match against alphaNumeric
words.. Limiting the vocabularly would enhance its chance of success..
how could i modify the given code to fulfill my requirement
Thanks in advance..
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakButton = (Button) findViewById(R.id.btn_speak);
mText = (TextView) findViewById(R.id.textView1);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getClass().getPackage().getName());
SpeechRecognizer recognizer = SpeechRecognizer
.createSpeechRecognizer(this.getApplicationContext());
RecognitionListener listener = new RecognitionListener() {
#Override
public void onResults(Bundle results) {
ArrayList<String> voiceResults = results
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if (voiceResults == null) {
Log.e(TAG, "No voice results");
} else {
Log.d(TAG, "Printing matches: ");
for (String match : voiceResults) {
Log.d(TAG, match);
mText.setText("results: " + match);
}
}
}
#Override
public void onReadyForSpeech(Bundle params) {
Log.d(TAG, "Ready for speech");
}
#Override
public void onError(int error) {
Log.d(TAG,
"Error listening for speech: " + error);
}
#Override
public void onBeginningOfSpeech() {
Log.d(TAG, "Speech starting");
}
#Override
public void onBufferReceived(byte[] buffer) {
// TODO Auto-generated method stub
}
#Override
public void onEndOfSpeech() {
// TODO Auto-generated method stub
}
#Override
public void onEvent(int eventType, Bundle params) {
// TODO Auto-generated method stub
}
#Override
public void onPartialResults(Bundle partialResults) {
// TODO Auto-generated method stub
}
#Override
public void onRmsChanged(float rmsdB) {
// TODO Auto-generated method stub
}
};
recognizer.setRecognitionListener(listener);
recognizer.startListening(intent);
/* speakButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
getClass().getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
sr.startListening(intent);
// startActivityForResult(intent, 1010);
Log.i("111111", "11111111");
}
});*/
}
}
You can not restrict recognition in Android Speech API, it doesn't support grammars. However, you can try CMUSphinx. See the example under link, you can define a grammar to use alpha digits only, it will work offline so the response will be very fast and you can tune accuracy for the best match too.

Parse.com How to add a ParseUser to Current User for a friendlist

In my application I'm trying to make a friendlist that's relative to the CurrentUser,I've tried looking through the docs of Parse.com and I asked a question about this on Parse.com and a Parser suggested I do it in the form of a Array column.I've done this although it seems to be relative to the CurrentUser(I made 3 accounts and made them friend eachother and the 3 accounts have different array columns retrieved from the ListView)It's not what I'm looking for since it's just the Usernames of the accounts and not their individual "rows" to make actions on the Users if you know what I mean.
So the question I'm asking is,
What would be the best practice using the Parse backend database to make a User "friendlist" based on the CurrentUser method?
Here is my 2 activities in which FindFriends is where I search for the Users and Add them to the "friendlist" and the PlayAFriend in which the friended Users would load up via an AdapterArray listview.
FindFriends Class
package com.fullfrontalgames.numberfighter;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.urbanairship.UAirship;
public class Findfriends extends Activity {
protected static final String TAG = null;
ParseObject po;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
final EditText sbar = (EditText)findViewById(R.id.PlayerSeachBar);
Button search = (Button)findViewById(R.id.Search);
Button Add = (Button)findViewById(R.id.Add);
final TextView ResultText = (TextView)findViewById(R.id.ResultTextView);
final FrameLayout ResultFrame = (FrameLayout)findViewById(R.id.ResultFrameLayout);
ResultFrame.setVisibility(View.GONE);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String username = sbar.getText().toString();
final ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("username", username);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
// TODO Auto-generated method stub
try {
ParseObject userObject = objects.get(0);
ResultText.setText(userObject.getString("username"));
ResultFrame.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Player Found",
Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(getApplicationContext(), "Username Not Found",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Friends = sbar.getText().toString();
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
{
currentUser.add("friend", Friends);
currentUser.saveInBackground();
Toast.makeText(getApplicationContext(), "Player Has Been Added",
Toast.LENGTH_LONG).show();
}
}
}
});
}
#Override
public void onStop() {
super.onStop();
}
}
PlayAFriend Class
package com.fullfrontalgames.numberfighter;
import java.util.ArrayList;
import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.urbanairship.UAirship;
public class PlayAFriend extends ListActivity {
private static final String TAG = null;
Cursor fFriends;
DBAdapter db;
ParseObject objects;
int from;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playafriend);
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
ArrayList<String> friendslist = new ArrayList<String>();
final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
ListView friendlv = (ListView)findViewById(android.R.id.list);
friendlv.setAdapter(listAdapter);
String friend = currentUser.get("friend").toString();
listAdapter.add(friend);
}
}
}
I solved question myself using the ParseRelation method from the docs.Here is my example on how to add a friend to the current user!
FindFriends class
public class Findfriends extends Activity {
protected static final String TAG = null;
ParseObject po;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.findfriends);
final EditText sbar = (EditText)findViewById(R.id.PlayerSeachBar);
Button search = (Button)findViewById(R.id.Search);
Button Add = (Button)findViewById(R.id.Add);
final TextView ResultText = (TextView)findViewById(R.id.ResultTextView);
final FrameLayout ResultFrame = (FrameLayout)findViewById(R.id.ResultFrameLayout);
ResultFrame.setVisibility(View.GONE);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final String username = sbar.getText().toString();
final ParseQuery query = ParseUser.getQuery();
query.whereEqualTo("username", username);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
// TODO Auto-generated method stub
try {
ParseObject userObject = objects.get(0);
ResultText.setText(userObject.getString("username"));
ResultFrame.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Player Found",
Toast.LENGTH_LONG).show();
} catch (Exception e2) {
e2.printStackTrace();
Toast.makeText(getApplicationContext(), "Username Not Found",
Toast.LENGTH_LONG).show();
}
}
});
}
});
Add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String Friends = sbar.getText().toString();
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
{
final ParseObject friend = new ParseObject("Friends");
friend.put("username", Friends);
friend.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
// TODO Auto-generated method stub
ParseRelation relation = currentUser.getRelation("Friends");
relation.add(friend);
currentUser.saveInBackground();
}
});
Toast.makeText(getApplicationContext(), "Player Has Been Added",
Toast.LENGTH_LONG).show();
}
}
}
});
}
#Override
public void onStop() {
super.onStop();
}
}
PlayAFriend Class
public class PlayAFriend extends ListActivity {
private static final String TAG = null;
ParseObject objects;
#Override
public void onStart() {
super.onStart();
UAirship.shared().getAnalytics();
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.playafriend);
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
final ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1);
ListView friendlv = (ListView)findViewById(android.R.id.list);
Button play = (Button)findViewById(android.R.id.button1);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
friendlv.setAdapter(listAdapter);
ParseRelation relation = currentUser.getRelation("Friends");
ParseQuery query = relation.getQuery();
query.whereEqualTo("username", null);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
// TODO Auto-generated method stub
for (int i = 0; i < objects.size(); i++) {
ParseObject r = objects.get(i);
String name = r.getString("username").toString();
listAdapter.add(name);
}
}
});
}
}
}
useing the Rest API docs approach, building on the reply you have from a parser,
you may want to link an array:friends as an object in your user class.
The friends object contains an array of pointers to the OID's in User class of all the friends of that user in the given user row.
You can update the array of pointers as you please by adding or removing objects from the array.
'{"friends":{"__op":"Add","objects":[{"__type":"Pointer",
"className":"User","objectId":"rtbhCb37tq"}]}}'
When you want to get the full , child user rows of all the friends of a given User ID ,
you just append the following to a normal query for a single row from the User table...
--data-urlencode 'include=friends'
The parse RestAPI Docs has some good examples of this technique involving Games, GameScores, and GameOpponents. You could read that.
If you want to eval the most advanced clients i would start with 'okhttp' and 'volley'.
More traditional http stuff here and here
I have reviewed your answer and I believe you may be able to improve the code a bit.
I found that you create a ParseObject friend and provide it with the attribute "username" which is retrieved with String Friends = sbar.getText().toString();, and then proceed to create a relation between that newly created ParseObject and the current ParseUser (currentUser).
The problem I found is within the Parse DB Storage. If you review your Parse DB you will find that the ParseObject friend that you are creating does not share the same ObjectID, or any of the attributes/data as the ParseUser that you are initially querying for.
You basically make a ParseObject that is no more than a copy of a ParseUser's username. I also found that you can add the same ParseObject friend multiply times, because everytime you do so you create a new ParseObject with a separate ObjectID and thus referencing a totally different ParseObject.
Ideally you would be looking to reference the ParseUser directly and I believe I have figured out how to do so.
Here is the entire Adapter that I have defined, but it allows you to create a relation with a ParseUser directly rather than having to create a ParseObject
public UserQueryAdapter(Context context, final String searchCriteria) {
// Use the QueryFactory to construct a PQA that will only show
// Todos marked as high-pri
super(context, new ParseQueryAdapter.QueryFactory<ParseUser>() {
public ParseQuery<ParseUser> create() {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereContains("username", searchCriteria);
return query;
}
});
}
#Override
public View getItemView(final ParseUser pUser, View v, ViewGroup parent) {
if (v == null) {
v = View.inflate(getContext(), R.layout.search_detail, null);
}
super.getItemView(pUser, v, parent);
ParseImageView todoImage = (ParseImageView) v
.findViewById(R.id.imageViewSearch);
ParseFile imageFile = pUser.getParseFile("photo");
if (imageFile != null) {
todoImage.setParseFile(imageFile);
todoImage.loadInBackground();
}
// Add the title view
final TextView titleTextView = (TextView) v
.findViewById(R.id.textViewSearch);
titleTextView.setText(pUser.getUsername());
btnAdd = (ImageButton) v.findViewById(R.id.imageButtonAdd);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Drawable background = v.getResources().getDrawable(
R.drawable.ui_border_green);
Drawable img = v.getResources().getDrawable(
R.drawable.ico_friend_add_green);
btnAdd.setBackground(background);
btnAdd.setImageDrawable(img);
final ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
{
ParseRelation<ParseUser> relation = currentUser
.getRelation("Friends");
relation.add(pUser);
currentUser.saveInBackground();
}
}
}
});
return v;
}

Categories

Resources