isEmpty() always returning true - android

I was making a form on android. While checking for the text fields, I used isEmpty() method to check if there was any text. The problem is, it is always returning true. I'm unable to figure out where I went wrong. Thanks in advance! :)
If any other file is needed, please comment here, I'll add it ASAP.
AddQuestionActivity.java
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_ANSWER;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_HINT;
import static chipset.quizzy.questionadder.resources.Constants.KEY_QUESTION_NUMBER;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import chipset.quizzy.questionadder.R;
import chipset.quizzy.questionadder.resources.Functions;
import chipset.quizzy.questionadder.resources.ShowImageActivity;
public class AddQuestionActivity extends Activity {
Functions functions = new Functions();
EditText addQuestionNumber, addQuestion, addQuestionAnswer,
addQuestionHint;
Button addQuestionImage, addQuestionAdd;
ImageView addQuestionImageView;
private static int RESULT_LOAD_IMAGE = 1;
String picturePath, question, questionNumber, questionAnswer, questionHint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_question);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
addQuestionNumber = (EditText) findViewById(R.id.addQuestionNumber);
addQuestion = (EditText) findViewById(R.id.addQuestion);
addQuestionAnswer = (EditText) findViewById(R.id.addQuestionAnswer);
addQuestionHint = (EditText) findViewById(R.id.addQuestionHint);
addQuestionImage = (Button) findViewById(R.id.addQuestionImage);
addQuestionImageView = (ImageView) findViewById(R.id.addQuestionImageView);
addQuestionAdd = (Button) findViewById(R.id.addQuestionAdd);
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
addQuestionAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
functions.hideKeyboard(getApplicationContext(),
getCurrentFocus());
if (functions.isConnected(getApplicationContext())) {
if (questionNumber.isEmpty() || question.isEmpty()
|| questionAnswer.isEmpty()
|| questionHint.isEmpty()) {
Toast.makeText(getApplicationContext(),
"Enter All Fields", Toast.LENGTH_SHORT).show();
Log.i(KEY_QUESTION, String.valueOf(question.isEmpty()));
Log.i(KEY_QUESTION_ANSWER,
String.valueOf(questionAnswer.isEmpty()));
Log.i(KEY_QUESTION_HINT,
String.valueOf(questionHint.isEmpty()));
Log.i(KEY_QUESTION_NUMBER,
String.valueOf(questionNumber.isEmpty()));
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
AddQuestionActivity.this);
builder.setTitle("Information");
builder.setMessage(KEY_QUESTION_NUMBER + " : "
+ questionNumber + "\n" + KEY_QUESTION + " : "
+ question + "\n" + KEY_QUESTION_ANSWER + " : "
+ questionAnswer + "\n" + KEY_QUESTION_HINT
+ " : " + questionHint + "\n");
builder.setNeutralButton(android.R.string.ok, null);
builder.create();
builder.show();
}
} else {
Toast.makeText(getApplicationContext(),
"No Internet Connection", Toast.LENGTH_SHORT)
.show();
}
}
});
addQuestionImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent addImage = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(addImage, RESULT_LOAD_IMAGE);
}
});
addQuestionImageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent loadBigImage = new Intent(getApplication(),
ShowImageActivity.class);
loadBigImage.putExtra("picturePath", picturePath);
startActivity(loadBigImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
addQuestionImageView.setVisibility(View.VISIBLE);
addQuestionImageView.setImageBitmap(BitmapFactory
.decodeFile(picturePath));
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_logout) {
functions.logout(getApplication(), getApplicationContext());
} else if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
activity_add_question.xml
<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="#color/turquoize" >
<TextView
android:id="#+id/addTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal|center_vertical"
android:text="#string/app_name"
android:textColor="#color/clouds"
android:textSize="30sp" />
<ScrollView
android:id="#+id/boxy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/addTitle"
android:layout_margin="15dp"
android:background="#color/clouds"
android:orientation="vertical"
android:padding="15dp"
tools:ignore="UselessLeaf" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="#+id/addQuestionNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/qNo"
android:inputType="number" />
<EditText
android:id="#+id/addQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/q"
android:inputType="textMultiLine" />
<EditText
android:id="#+id/addQuestionAnswer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/qAns"
android:inputType="text" />
<EditText
android:id="#+id/addQuestionHint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/qHint"
android:inputType="text" />
<Button
android:id="#+id/addQuestionImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:background="#drawable/button_click"
android:text="#string/uQImage"
android:textColor="#color/turquoize" />
<ImageView
android:id="#+id/addQuestionImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:background="#color/black"
android:contentDescription="#string/qImage"
android:visibility="gone" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/addQuestionAdd"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="15dp"
android:background="#drawable/button_click"
android:text="#string/addQuestionDo"
android:textColor="#color/turquoize" />
</RelativeLayout>

You need to move this under your Button onClick(...) event
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
Update
Just like so
addQuestionAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
...........
.............
}
});

It is because, in the onCreate stage itself you are getting the values of the text box and storing it in a variable. Initially the text box would be empty and hence the value would also be empty.
So Modify your onclick Listener code, so that you get the text box value inside the code and then process it. However, also check inside the onclicklistener for empty strings because the user might not have input any value to the textbox. :)
// Edit text instance can be declared in the onCreate
protected void onCreate(Bundle savedInstanceState)
{
....
addQuestionNumber = (EditText) findViewById(R.id.addQuestionNumber);
addQuestion = (EditText) findViewById(R.id.addQuestion);
addQuestionAnswer = (EditText) findViewById(R.id.addQuestionAnswer);
addQuestionHint = (EditText) findViewById(R.id.addQuestionHint);
....
}
// Edit Text value getting should be inside onClick
public void onClick(View v) {
questionNumber = addQuestionNumber.getText().toString().trim();
question = addQuestion.getText().toString().trim();
questionAnswer = addQuestionAnswer.getText().toString().trim();
questionHint = addQuestionHint.getText().toString().trim();
...
}

Related

Data not being added to Firebase, Data not being passed through Intent and !TextUtils.isEmpty not working

So I am creating an events app using Firebase as my database. I am an amateur developer so please bear with me. There are 3 main problems that I have been facing:
1) My main problem is that data is not being written to Firebase. I have changed the rules to 'true' in the database module. I also have an image input by the user which is being uploaded, but the data such as event_title and others is not being uploaded
2) I have used Intent to pass data from one activity to another but it is not passing. I used a textView on the next Activity to setText, but it changes to null. The data is also not shwoing in the Log, as much I know about Log.d
3) I don't for what reason !TextUtils.isEmpty is not working on my CreateEvent2. I need to comment the entire if - condition to go to the CreateEvent3. However it is working in CreateEvent3.java.
I tried a lot of methods but I do not know for what reasons these errors are coming.
Here is my code:
CreateEvent2.java
package com.example.admin.college20;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class CreateEvent2 extends AppCompatActivity {
private EditText mEventTitle, mEventLocation, mEventCategory, mContact;
private Button mNextButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event2);
mEventTitle = (EditText) findViewById(R.id.event_title);
mEventLocation = (EditText) findViewById(R.id.event_location);
mEventCategory = (EditText) findViewById(R.id.event_category);
mContact = (EditText) findViewById(R.id.contact_info);
mNextButton = (Button) findViewById(R.id.nextButton);
final String event_title = mEventTitle.getText().toString().trim();
final String event_location = mEventLocation.getText().toString().trim();
final String event_category = mEventCategory.getText().toString().trim();
final String contact = mContact.getText().toString().trim();
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/**if (!TextUtils.isEmpty(event_title)
&& !TextUtils.isEmpty(event_location)
&& !TextUtils.isEmpty(event_category)
&& !TextUtils.isEmpty(contact)) {**/
Intent i = new Intent(CreateEvent2.this, CreateEvent3.class);
i.putExtra("title", event_title);
i.putExtra("location", event_location);
i.putExtra("category", event_category);
i.putExtra("contact", contact);
startActivity(i);
}
});
}
}
activity_create_event2.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.admin.college20.CreateEvent2"
android:background="#drawable/create_event_1">
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Event Title"
android:layout_marginTop="90dp"
android:id="#+id/event_title"
android:inputType="textMultiLine"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/event_location"
android:layout_alignEnd="#+id/event_location" />
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Event Location"
android:id="#+id/event_location"
android:inputType="textMultiLine"
android:layout_centerVertical="true"
android:layout_alignLeft="#+id/contact_info"
android:layout_alignStart="#+id/contact_info" />
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Event Category"
android:id="#+id/event_category"
android:inputType="textMultiLine"
android:layout_marginTop="32dp"
android:layout_below="#+id/event_location"
android:layout_alignLeft="#+id/contact_info"
android:layout_alignStart="#+id/contact_info" />
<EditText
android:layout_width="300dp"
android:layout_height="50dp"
android:hint="Contact Number"
android:id="#+id/contact_info"
android:inputType="textMultiLine"
android:layout_above="#+id/nextButton"
android:layout_marginBottom="20dp"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="50dp"
android:text="New Button"
android:id="#+id/nextButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="27dp" />
</RelativeLayout>
CreateEvent3.java
package com.example.admin.college20;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class CreateEvent3 extends AppCompatActivity {
private EditText mEventDesc, mEventFBUrl, mEventWebLink;
private TextView hello;
private Button upload_image_button, done_button;
private ProgressDialog progressDialog;
private static final int GALLERY_INTENT = 1;
private Uri imageUri = null;
private DatabaseReference mDatabaseReference;
private StorageReference mStorageRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event3);
mEventDesc = (EditText) findViewById(R.id.event_desc);
mEventFBUrl = (EditText) findViewById(R.id.fb_event_url);
mEventWebLink = (EditText) findViewById(R.id.event_weblink);
upload_image_button = (Button) findViewById(R.id.upload_image_button);
done_button = (Button) findViewById(R.id.done_button);
hello = (TextView) findViewById(R.id.hello);
mDatabaseReference = FirebaseDatabase.
getInstance().
getReference().
child("Event");
mStorageRef = FirebaseStorage.getInstance().getReference();
progressDialog = new ProgressDialog(this);
upload_image_button.setVisibility(View.VISIBLE);
upload_image_button.setBackgroundColor(Color.TRANSPARENT);
upload_image_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
});
done_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startPosting();
Toast.makeText(CreateEvent3.this, "Button Selected", Toast.LENGTH_SHORT).show();
}
});
}
public void startPosting() {
progressDialog.setMessage("Uploading the Data");
Intent in = getIntent();
Bundle bundle = in.getExtras();
final String event_title = getIntent().getStringExtra("title");
final String event_location = getIntent().getStringExtra("location");
final String event_category = getIntent().getStringExtra("category");
final String contact = getIntent().getStringExtra("contact");
final String event_desc = mEventDesc.getText().toString().trim();
final String event_weblink = mEventWebLink.getText().toString().trim();
final String event_fb_url = mEventFBUrl.getText().toString().trim();
Log.d("Event Tile", event_title);
Log.d("Event Location", event_location);
Log.d("Event Category", event_category);
hello.setText(event_title);
if (!TextUtils.isEmpty(event_desc)
&& !TextUtils.isEmpty(event_weblink)
&& !TextUtils.isEmpty(event_fb_url)
&& imageUri != null) {
progressDialog.show();
StorageReference filepath = mStorageRef.child("Images").child(imageUri.getLastPathSegment());
filepath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri uri = taskSnapshot.getDownloadUrl();
DatabaseReference newEvent = mDatabaseReference.push();
newEvent.child("title").setValue(event_title);
newEvent.child("location").setValue(event_location);
newEvent.child("category").setValue(event_category);
newEvent.child("contact").setValue(contact);
newEvent.child("desc").setValue(event_desc);
newEvent.child("web").setValue(event_weblink);
newEvent.child("fb").setValue(event_fb_url);
newEvent.child("imageUrl").setValue(uri.toString());
progressDialog.dismiss();
startActivity(new Intent(CreateEvent3.this, MainPage1.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(CreateEvent3.this, "Upload Failed :(", Toast.LENGTH_SHORT).show();
}
});
}
else{
Toast.makeText(this, "Fill in the details", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
imageUri = data.getData();
}
}
}
activity_create_event3.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="com.example.admin.college20.CreateEvent3"
android:background="#drawable/create_event_2">
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/event_desc"
android:layout_marginTop="144dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:inputType="textMultiLine"
android:hint="Enter short description here..."
/>
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/fb_event_url"
android:layout_below="#+id/event_desc"
android:layout_alignLeft="#+id/event_desc"
android:layout_alignStart="#+id/event_desc"
android:layout_marginTop="134dp" />
<EditText
android:layout_width="300dp"
android:layout_height="wrap_content"
android:id="#+id/event_weblink"
android:layout_marginTop="49dp"
android:layout_below="#+id/fb_event_url"
android:layout_alignLeft="#+id/fb_event_url"
android:layout_alignStart="#+id/fb_event_url" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="300dp"
android:layout_height="60dp"
android:id="#+id/upload_image_button"
android:layout_marginTop="50dp"
android:layout_below="#+id/event_desc"
android:layout_alignLeft="#+id/event_desc"
android:layout_alignStart="#+id/event_desc" />
<Button
android:layout_width="120dp"
android:layout_height="wrap_content"
android:id="#+id/done_button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp" />
<TextView
android:text="Hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/event_desc"
android:layout_alignEnd="#+id/event_desc"
android:layout_marginRight="49dp"
android:layout_marginEnd="49dp"
android:layout_marginTop="33dp"
android:id="#+id/hello" />
</RelativeLayout>
The problem is that you're getting the text from the EditText on your CreateEvent2's onCreate method. You should get it on your OnClickListener. Like this:
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String event_title = mEventTitle.getText().toString().trim();
final String event_location = mEventLocation.getText().toString().trim();
final String event_category = mEventCategory.getText().toString().trim();
final String contact = mContact.getText().toString().trim();
if (!TextUtils.isEmpty(event_title)
&& !TextUtils.isEmpty(event_location)
&& !TextUtils.isEmpty(event_category)
&& !TextUtils.isEmpty(contact)) {
Intent i = new Intent(CreateEvent2.this, CreateEvent3.class);
i.putExtra("title", event_title);
i.putExtra("location", event_location);
i.putExtra("category", event_category);
i.putExtra("contact", contact);
startActivity(i);
}
}
});

Android EditText not editable

I have a 2 activities with edittexts on them the first activity work fine but the second activity's EditText is focused but I can't edit it nor can I click the button on it.
Also everything works in the emulator but not when I install it on the device. (The keyboard popup also does not come up in the second activity where as it does in the first activity)
Below is the code for the1st and second activity
First Activity Class
package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends ActionBarActivity {
EditText edtEmail, edtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Initialize components
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtPassword = (EditText) findViewById(R.id.edtPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtEmail.getText().toString().length() > 0 && edtPassword.getText().toString().length() > 0) {
new GetAllCustomerTask().execute(new ConnecterClass());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
// Connect to the DB
private class GetAllCustomerTask extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].usrLogin(edtEmail.getText().toString(), edtPassword.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(0);
if (edtEmail.getText().toString().equals(json.getString("email"))) {
if (edtPassword.getText().toString().equals(json.getString("pass"))) {
Toast toast = Toast.makeText(getApplicationContext(), "login successful", Toast.LENGTH_SHORT);
toast.show();
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
//Pass the school_id
intent.putExtra("SCHOOL_ID", json.getInt("school_id"));
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "password incorrect", Toast.LENGTH_SHORT);
toast.show();
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), "failed to login ...", Toast.LENGTH_SHORT);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
Second Activity Class
> package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SearchActivity extends ActionBarActivity {
EditText edtFName, edtLName, edtIDNum;
ListView listViewSearch;
String sFName, sLName, sIDNum;
int school_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
edtFName = (EditText) findViewById(R.id.edtFirstName);
edtLName = (EditText) findViewById(R.id.edtLastName);
edtIDNum = (EditText) findViewById(R.id.edtIDNum);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
listViewSearch = (ListView) this.findViewById(R.id.listViewSearch);
//Initialize the default values for the search criteria variables
sFName = "";
sLName = "";
sIDNum = "";
//Load school_id
school_id = getIntent().getExtras().getInt("SCHOOL_ID");
if(edtFName.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); }
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtFName.getText().toString().length() > 0)
{
sFName = edtFName.getText().toString().trim();
}
if(edtLName.getText().toString().length() > 0)
{
sLName = edtLName.getText().toString().trim();
}
if(edtIDNum.getText().toString().length() > 0)
{
sIDNum = edtIDNum.getText().toString().trim();
}
new SearchAllCustomers().execute(new ConnecterClass());
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//Search in the background
public void setListViewArray(final JSONArray jsonArray)
{
this.listViewSearch.setAdapter(new Search_ListView_Adapter(jsonArray, this));
//Setup what happens when a user clicks on a searched item
this.listViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
JSONObject clickedItem = jsonArray.getJSONObject(position);
Intent askActivity = new Intent(getApplicationContext(), AskActivity.class);
askActivity.putExtra("IDNUM", clickedItem.getString("idnum"));
askActivity.putExtra("SCHOOL_ID", clickedItem.getInt("school_id"));
startActivity(askActivity);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Connect to the DB
private class SearchAllCustomers extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].searchPlayers(school_id, sFName, sLName, sIDNum);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
setListViewArray(jsonArray);
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
The XML - First Activity
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginAcivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/edtEmail"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:hint="email ..."
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/edtPassword"
android:layout_below="#+id/edtEmail"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:hint="password ..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btnLogin"
android:layout_below="#+id/edtPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp" />
</RelativeLayout>
The XML - Second Activity
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.rohan.rohan_pc.sportsappv001.SearchActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Search"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/edtFirstName"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Surname"
android:ems="10"
android:id="#+id/edtLastName"
android:layout_below="#+id/edtFirstName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edtIDNum"
android:hint="ID Number"
android:layout_below="#+id/edtLastName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/edtLastName"
android:layout_alignEnd="#+id/edtLastName" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btnSearch"
android:layout_below="#+id/edtIDNum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="42dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:id="#+id/listViewSearch"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/edtIDNum"
android:layout_alignTop="#+id/edtFirstName"
android:clickable="true"
/>
I just figured to re-create the app. I dont think it is a wise decision to copy the raw files to another directory and use that.

how to select msg display in edit box and create txt file in application

I have created a list, messagebox and main activity java file.
when user clicks on inbox button show all inbox msg of your mobile.
when you select inbox msg that display on automatically my mainactivity.java in edit box and when you click save button the create text(.txt) file in my application
I forward to all xml file and it is important how to select msg automatically display on edit box and when click on save create .txt file in application.
when you click on save button those of edit box msg create txt file and txt file data is same edit box msg.
**Mainactivity.java**
package com.example.sharedpreference;
import com.example.sharedpreference.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button send,checkdata,Inbox,checkmsg;
private EditText phoneno,editText2;
private TextView Display,message,SMSm;
//private Button save;
String Message,PhoneNo,SMSBody1,phoneNumber1;
/*public void getSmsDeatils(String SMSBody,String phoneNumber){
SMSBody1=SMSBody;
phoneNumber1=phoneNumber;
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phoneno = (EditText) findViewById(R.id.editText1);
editText2 = (EditText) findViewById(R.id.editText2);
Display = (TextView) findViewById(R.id.EditText1);
message = (TextView) findViewById(R.id.textView2);
//SMSm=(TextView) findViewById (R.id.etSmsBody);
//Inbox=(Button) findViewById(R.id.inbox);
send=(Button) findViewById(R.id.send);
checkdata=(Button) findViewById(R.id.checkdata);
//checkmsg=(Button) findViewById(R.id.button1);
checkdata.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
PhoneNo=phoneno.getEditableText().toString();
Message=message.getText().toString();
/*Intent intent = new Intent(context,MainActivity.class);
startActivity(intent);*/
Display.setText("Phone Number-:"+PhoneNo+"\n"+"Message-:"+Message);
//display.setVisibility(View.VISIBLE);
}
});
/*Inbox.setOnClickListener(new OnClickListener() {
private Context context;
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,MessageBox.class);
startActivity(intent);
}
});*/
Intent i = getIntent();
String val = "";
if(i.hasExtra("value"))
val = i.getStringExtra("value");
editText2 = (EditText) findViewById(R.id.editText2);
editText2.setText(val);
//checkmsg=(Button) findViewById(R.id.checkmsg);
/*checkmsg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Object result = editText2.getText().toString();
Intent i = new Intent();
i.putExtra("MESSAGE", (Boolean) result);
Intent in = null;
startActivity(in);
}
});*/
Inbox=(Button) findViewById(R.id.inbox);
Inbox.setOnClickListener(new View.OnClickListener() {
//private Context context;
#Override
public void onClick(View v) {
//Intent intent = new Intent(getApplicationContext(), MessageBox.class);
// TODO Auto-generated method stub
//Intent intent = new Intent(context,MessageBox.class);
//startActivity(intent);
Intent intent = new Intent(MainActivity.this, MessageBox.class);
startActivity(intent);
}
});
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sendSMSMessage();
}
//#TargetApi(Build.VERSION_CODES.DONUT)
//#SuppressLint("NewApi")
private void sendSMSMessage() {
// TODO Auto-generated method stub
Log.i("SEND SMS","");
String message=Display.getText().toString();
try{
SmsManager smsManager=SmsManager.getDefault();
smsManager.sendTextMessage("7666433328", null,message,null,null);
Toast.makeText(getApplicationContext(),"SMS Sent",Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(getApplicationContext(),"SMS Failed,please try again",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
MessageBox.java
package com.example.sharedpreference;
/***
* Application Name : MessageBox
* Author : Vimal Rughani
* Website : http://pulse7.net
* For more details visit http://pulse7.net/android/read-sms-message-inbox-sent-draft-android/
*/
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
public class MessageBox extends Activity implements OnClickListener {
// GUI Widget
Button btnSent, btnInbox, btnDraft;
TextView lblMsg, lblNo;
ListView lvMsg;
// Cursor Adapter
SimpleCursorAdapter adapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagebox);
// Init GUI Widget
btnInbox = (Button) findViewById(R.id.btnInbox);
btnInbox.setOnClickListener(this);
lvMsg = (ListView) findViewById(R.id.lvMsg);
}
#Override
public void onClick(View v) {
if (v == btnInbox) {
// Create Inbox box URI
Uri inboxURI = Uri.parse("content://sms/inbox");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Inbox SMS Message from Built-in Content Provider
Cursor c = cr.query(inboxURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address" }, new int[] {
R.id.lblMsg, R.id.lblNumber });
lvMsg.setAdapter(adapter);
}
/*if (v == btnSent) {
// Create Sent box URI
Uri sentURI = Uri.parse("content://sms/sent");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = cr.query(sentURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address" }, new int[] {
R.id.lblMsg, R.id.lblNumber });
lvMsg.setAdapter(adapter);
}
if (v == btnDraft) {
// Create Draft box URI
Uri draftURI = Uri.parse("content://sms/draft");
// List required columns
String[] reqCols = new String[] { "_id", "address", "body" };
// Get Content Resolver object, which will deal with Content
// Provider
ContentResolver cr = getContentResolver();
// Fetch Sent SMS Message from Built-in Content Provider
Cursor c = cr.query(draftURI, reqCols, null, null, null);
// Attached Cursor with adapter and display in listview
adapter = new SimpleCursorAdapter(this, R.layout.row, c,
new String[] { "body", "address" }, new int[] {
R.id.lblMsg, R.id.lblNumber });
lvMsg.setAdapter(adapter);
}*/
}
}
list.java
package com.example.sharedpreference;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class list extends ListActivity implements OnClickListener{
TextView txt;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.row);
String[] items = null;
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items));
txt = (TextView) findViewById(R.id.lblMsg);
txt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
/*
result = txt.getText().toString();
Intent i = new Intent();
i.putExtra("MessageFromsecondActivity", result);
setResult(1, i);
finish();
*/
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// TODO Auto-generated method stub
String val = ((TextView) v).getText().toString().trim();
CharSequence[] items = null;
txt.setText(items[position]);
Intent i = new Intent(list.this, MessageBox.class);
i.putExtra("value", val);
//Intent in = null;
startActivity(i);
}
/* #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}*/
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
all xml files
this is my activity_xml file. In select msg from Inbox that display on edit box and when create save button generate txt file in my application
<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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/text_id"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:capitalize="characters"
android:text="Please Enter your phone no "
android:gravity="center"
android:background="#00FFFF"
android:textColor="#000000"
android:textSize="20dp"
/>
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/text_id"
android:ems="10"
android:inputType="number"
android:maxLength="10" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/editText1"
android:text="Message"
android:textSize="20dp"
android:textColor="#000000"
android:background="#00FFFF"
android:gravity="center" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:text="Please check my Information in eTMS"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/textView2"
android:text="send" />
<Button
android:id="#+id/checkdata"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/send"
android:text="Check Data" />
<TextView
android:id="#+id/EditText1"
android:layout_width="300dp"
android:layout_height="75dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/send"
android:layout_weight="1"
android:ems="7"
android:textStyle="bold" />
<Button
android:id="#+id/inbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/EditText1"
android:layout_alignParentLeft="true"
android:text="Inbox" />
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/EditText1"
android:layout_toRightOf="#+id/inbox"
android:text="Msg Check" />
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/EditText1"
android:ems="10"
android:inputType="textPersonName" />
</RelativeLayout >
Code to write to file present in EditText
Just call below method in onclick event of save button
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}

Android speech to text using listview

The code below is used to convert speech to text on an android app. This code works when the speech button is pressed and whatever you say is transferred into text.
When the speech function closes, the the text is showing.
If you hit the speech button again, the previous text is cleared and the new text shows on the page. What i want to do is everytime i click the speak button, i want to show the word on the page.. then if i click the speak button again, i want the next word to appear under the first word in a list format.
i am looking to use listview but am struggling. here is the original code and the code i am trying to write to make it a listview. can anyone assist?
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_toLeftOf="#+id/textView1"
android:gravity="center"
android:orientation="vertical" >
<ImageButton
android:id="#+id/btnSpeak"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:contentDescription="#string/speak"
android:src="#android:drawable/ic_btn_speak_now" />
<TextView
android:id="#+id/txtText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Code:
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Ops! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
In your onActivityResult, you are overriding your TextView with the first word only(index 0).
You must iterate through the String array list like so:
String words = "";
for ( String word : text ) {
words += " " + word;
}
txtText.setText(words);
And here's a nice article to help you implement your ListView:
ListView tutorial
So now when you figured that out you add the words value in the listview.
Hope this helps,
Cheers

Cannot read EditText in fragment class

I have two tabs and each tab is a Fragment. In one of the fragments (Afragment.claas) I have a dialog box to insert some data, and I want to save them in a database. When I fill the text fields and press OK, the application stops.
I think when I initialize the edittext there is something wrong.
name = (EditText) activity.findViewById(R.id.etProviderName);
The above statement is returning null
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Afragment extends ListFragment {
DBAdapter db;
Activity activity;
private static final String fields[] = { "provider._providerName", "_providerMobile" };
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initAdapter();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
add();
return (true);
case R.id.menu_reset:
initAdapter();
return (true);
case R.id.menu_info:
Toast.makeText(activity, "Developed By Omar Al-Shammary", Toast.LENGTH_LONG)
.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
// TODO Auto-generated method stub
System.out.println("insider Add Method");
final View addView = activity.getLayoutInflater().inflate(R.layout.add_provider, null);
new AlertDialog.Builder(activity).setTitle("Add a Provider").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.out.println("Befor calling insert in providers");
insertInProviders();
System.out.println("after calling insert in providers");
}
}).setNegativeButton("Cancel", null).show();
initAdapter();
}
private void initAdapter() {
activity = getActivity();
db = new DBAdapter(activity);
fillTheList();
}
public void fillTheList()
{
db.open();
Cursor data = db.getAllProviders();
CursorAdapter dataSource = new SimpleCursorAdapter(activity,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
setListAdapter(dataSource);
db.close();
setListAdapter(dataSource);
}
public void insertInProviders()
{
EditText name,location,number;
name = (EditText) activity.findViewById(R.id.etProviderName);
location = (EditText) activity.findViewById(R.id.etProviderName);
number = (EditText) activity.findViewById(R.id.etProviderName);
if(name == null)
System.out.println("EditeText name is null");
String provName = name.getText().toString();
if(location == null)
System.out.println("location is null");
String provLocation = location.getText().toString();
String provNumber = number.getText().toString();
System.out.println("Before Open");
db.open();
System.out.println("Before DB.Insert");
db.insertProvider(provName, provLocation, provNumber);
System.out.println("Before Close");
db.close();
}
}
add_provider.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvProviderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="#+id/etProviderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvProvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
<EditText
android:id="#+id/etProvLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvProvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number" />
<EditText
android:id="#+id/etProvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>
This is the code I use for declaring buttons in Fragments - maybe it can help you.
What I would do is access the inflated layout and then you should be able to access items underneath it. Let me know if that makes sense.
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.frag1_button);
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
}
});
return theLayout;
So maybe you should try this since you inflate your View as "addView"
name = (EditText) addView.findViewById(R.id.etProviderName);
The findViewById should not be called by the activity but by the enclosing view. You should have something like:
In the class
View aView;
In the method:
LayoutInflater inflater = getActivity().getLayoutInflater();
aView = inflater.inflate(R.layout.add_provider, null);
...
EditText name = (EditText) aView.findViewById(R.id.etProviderName);
I hope it helps.

Categories

Resources