My homework is a Text to speech app using Spinner choose Language.
but I do not know very much about this topic.
Here my code for MainActivity.java:
package com.detainhom6.doctext;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class MainActivity extends Activity implements OnInitListener{
// Khai bao cac bien can thiet
String chuoinhap;
String ngonngu[] = {"English", "Japan", "Korea", "China"};
EditText txtNhap;
Button btnNoi;
Toast note;
Spinner spnn;
//Khai bao bien text to speech
private TextToSpeech t2p;
private int kiemtradulieu = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// gan gia tri cho bien vua khai bao
txtNhap = (EditText)findViewById(R.id.txtnhap);
btnNoi = (Button)findViewById(R.id.btnNoi);
spnn = (Spinner)findViewById(R.id.menungonngu);
//
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, ngonngu);
adapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spnn.setAdapter(adapter);
spnn.setOnItemSelectedListener(new ClickChonNgonNgu());
Intent kiemtrat2pintent = new Intent();
kiemtrat2pintent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(kiemtrat2pintent, kiemtradulieu);
btnNoi.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View mangV) {
// TODO Auto-generated method stub
chuoinhap = txtNhap.getText().toString();
doc(chuoinhap);
}
});
}
// Tao Ham khi Goi Intent Acivity Result
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == kiemtradulieu){
if(resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS){
t2p = new TextToSpeech(this,this);
}
else
{
Intent caidatt2pIntent = new Intent();
caidatt2pIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(caidatt2pIntent);
}
}
}
// Khoi Tao Ham Doc Chuoi Da Nhap
protected void doc(String chuoinhap2) {
// TODO Auto-generated method stub
t2p.speak(chuoinhap2, TextToSpeech.QUEUE_FLUSH, null);
}
// Tao su kien khi chon item trong Spinner
public class ClickChonNgonNgu implements OnItemSelectedListener{
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String nndachon;
nndachon = ngonngu[position];
if(nndachon == "English"){
t2p.setLanguage(Locale.US);
note = Toast.makeText(MainActivity.this, "Bạn Dã Chọn English", Toast.LENGTH_SHORT);
note.setGravity(Gravity.CENTER, 0, 0);
note.show();
}
if(nndachon == "Japan"){
t2p.setLanguage(Locale.JAPAN);
note = Toast.makeText(MainActivity.this, "Bạn đã chọn Japan", Toast.LENGTH_SHORT);
note.setGravity(Gravity.CENTER, 0, 0);
note.show();
}
if(nndachon == "Korea"){
t2p.setLanguage(Locale.KOREA);
note = Toast.makeText(MainActivity.this, "Bạn đã chọn Korea", Toast.LENGTH_SHORT);
note.setGravity(Gravity.CENTER, 0, 0);
note.show();
}
if(nndachon == "China"){
t2p.setLanguage(Locale.CHINA);
note = Toast.makeText(MainActivity.this, "Bạn đã chọn China", Toast.LENGTH_SHORT);
note.setGravity(Gravity.CENTER, 0, 0);
note.show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
#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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status == TextToSpeech.SUCCESS)
{
t2p.setLanguage(Locale.US);
Log.e("TTS INIT", "TTS Thành Công");
}
else if(status == TextToSpeech.ERROR)
{
Log.e("TTS INIT", "TTS Lỗi");
}
}
}
And here is the activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.detainhom6.doctext.MainActivity" >
<TextView
android:id="#+id/txtnote"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/note1" />
<Button
android:id="#+id/btnNoi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtnhap"
android:layout_below="#+id/txtnhap"
android:layout_marginTop="21dp"
android:text="#string/Button_Noi" />
<EditText
android:id="#+id/txtnhap"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtnote"
android:layout_below="#+id/txtnote"
android:layout_marginTop="116dp"
android:ems="10"
android:hint="#string/hint_txt" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/menungonngu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtnhap"
android:layout_below="#+id/txtnote"
android:layout_marginTop="34dp" />
</RelativeLayout>
Can someone please help me fix code if you can?
Thanks so much!
Related
I am developing an android application, my proposal is have two clickable textviews on the page and when user press each of the textview, a listview in a popupwindow will shows under the textview, when user choose a listview item, the textview will be setText() as the name as user selected, when user perform long click on the textview or on the listview item, a contextmenu can be shown to allow user "edit"(jump to a new activity for that) or "delete" the selected item and after that the list adapter can update the list accordingly.
I have finished the code of registerContextMenu for the textview and it works, but the context menu won't show after I added the same code to the listview, I also tried add OnCreateContextMenuListener to the listview but failed again. can any expert help to look into this? thanks a lot.
here is the code:
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
/**
* #author Allen
*
*
*/
public class ProfileActivity extends Activity {
private TextView aTextView;
private TextView bTextView;
private View popupWindow;
// to initial popupwindow width and height
private final int popupWindowWidth = 400;
private final int popupWindowHeight = 350;
// the background drawable for popupWindow
ColorDrawable blackBackground = new ColorDrawable(Color.BLACK);
private PopupWindow aPW;
private ListView aListView;
private ArrayAdapter<String> aListViewAdapter;
private List<String> popupNameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
init();
Toast.makeText(this, "Long press item to modify", Toast.LENGTH_SHORT).show();
}
private void init() {
aTextView = (TextView) findViewById(R.id.aSelectionTextView);
aTextView.setText("Pls select");
aTextView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
//to bTextView will be the same process, only the popupnamelist //will be the different list
popupNameList = new ArrayList<String>();
popupWindow = this.getLayoutInflater().inflate(R.layout.profile_popup_window, null);
aPW = new PopupWindow(popupWindow, popupWindowWidth, popupWindowHeight);
addOnClickListeners();
}
private void aSelection() {
// TODO Auto-generated method stub
popupNameList = new ArrayList<String>();
popupNameList.add("abc");
popupNameList.add("ABC");
popupNameList.add("123");
// to enable the outside click dismiss the PW
aPW.setBackgroundDrawable(blackBackground);
aPW.setOutsideTouchable(true);
// to limit dispatching the click event.
aPW.setFocusable(true);
aListView = (ListView) popupWindow.findViewById(R.id.profile_popup_lstview);
aListViewAdapter = new ArrayAdapter<String>(this, R.layout.profile_listview_item, popupNameList);
aListView.setAdapter(aListViewAdapter);
aListView.setLongClickable(true);
this.registerForContextMenu(aListView);
aListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
aTextView.setText(popupNameList.get(position));
aPW.dismiss();
}
});
aListView.setOnCreateContextMenuListener(mListOnCreateContextMenuListener);
}
private void addOnClickListeners() {
// TODO Auto-generated method stub
aTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
aSelection();
aPW.showAsDropDown(findViewById(R.id.aSelectionTextView), 0, -10, Gravity.START);
}
});
this.registerForContextMenu(aTextView);
}
public void onLaunchDoneClick(View view) {
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
// menu.setHeaderTitle("Operation");
menu.add(0, 0, 0, getString(R.string.edit));
menu.add(0, 1, 0, getString(R.string.delete));
}
private final OnCreateContextMenuListener mListOnCreateContextMenuListener = new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
Toast.makeText(getApplicationContext(), "onCreateContextMenu()", 1000).show();
menu.add(0, 0, 0, getString(R.string.edit));
menu.add(0, 1, 0, getString(R.string.delete));
}
};
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case 0:
Toast.makeText(getApplicationContext(), popupNameList.get(menuInfo.position), 1000).show();
aListViewAdapter.notifyDataSetChanged();
break;
case 1:
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
}
The layout xml is here:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/bSelectionTextView"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignEnd="#+id/aSelectionTextView"
android:layout_alignStart="#+id/aSelectionTextView"
android:layout_toRightOf="#+id/textView2"
android:layout_below="#+id/aSelectionTextView"
android:gravity="start|center"
android:text="BSelectionTextView"
android:textSize="20sp" />
<Button
android:id="#+id/okButton"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#id/dSelectionTextView"
android:layout_centerHorizontal="true"
android:background="#drawable/my_button_style"
android:gravity="center"
android:onClick="onLaunchDoneClick"
android:text="#string/Done"
android:textSize="18sp"
android:visibility="gone" />
<TextView
android:id="#+id/textView1"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_marginTop="5dp"
android:layout_alignParentTop="true"
android:gravity="start|center"
android:text="ASelection"
android:textSize="18sp" />
<TextView
android:id="#+id/textView2"
android:layout_width="120dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="#id/textView1"
android:gravity="start|center"
android:text="BSelection"
android:textSize="18sp" />
<TextView
android:id="#+id/aSelectionTextView"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/textView1"
android:clickable="true"
android:gravity="start|center"
android:text="ASelectionTextView"
android:textSize="20sp" />
</RelativeLayout>
I have gone through a lot of links here, but yet i was not able to get my stuff working. Can you please help me fetch data from my custom list.
Details are as under :- My custom list view
<?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" >
<RadioGroup
android:id="#+id/radioGroup_option"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tv_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"/>
<RadioButton
android:id="#+id/rb_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<RadioButton
android:id="#+id/rb_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RadioGroup>
</LinearLayout>
I am populating a List through the UI the code for that is :-
package com.example.customadapter;
import java.lang.reflect.Array;
import java.util.Arrays;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
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.Toast;
public class CustomAdapter extends ActionBarActivity {
AddDataToArray mydata;
EditText qstno,qstn,opt1,opt2;
Button btn_save,btn_display;
int questio_no;
String question,option1,option2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_adapter);
mydata=AddDataToArray.getInstance();
qstno=(EditText)findViewById(R.id.edt_qstn_no);
qstn=(EditText)findViewById(R.id.edt_add_qstn);
opt1=(EditText)findViewById(R.id.edt_opt1);
opt2=(EditText)findViewById(R.id.edt_opt2);
btn_save=(Button)findViewById(R.id.btn_save);
btn_display=(Button)findViewById(R.id.btn_display);
btn_save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
questio_no=Integer.parseInt(qstno.getText().toString());
question=qstn.getText().toString();
option1=opt1.getText().toString();
option2=opt2.getText().toString();
System.out.println("Questio added in the UI --> "+ question);
String statusReceived=mydata.AddingQuestions(questio_no, question, option1, option2);
Toast.makeText(getApplicationContext(), statusReceived, Toast.LENGTH_LONG).show();
qstn.setText("");
opt1.setText("");
opt2.setText("");
}
});
btn_display.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (int i=0;i<mydata.myQstnList.size();i++)
{
System.out.println("Qustion no"+mydata.myQstnList.get(i).getQstno());
System.out.println("Question -->"+mydata.myQstnList.get(i).getQstn());
//System.out.println("The First Option added was:-" + mydata.myQstnList.get(i).getOpt1());
}
Intent myIntent = new Intent(CustomAdapter.this, Mediator.class);
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.custom_adapter, 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);
}
}
Finally i made an adapter from base adapter as follows:-
package com.example.customadapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<Question> mQuestion;
Context context;
public MyAdapter(Context context,List<Question> mQuestion) {
super();
this.context=context;
this.mQuestion = mQuestion;
this.mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mQuestion.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mQuestion.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
ViewHolder holder;
if (convertView == null){
view = mInflater.inflate(R.layout.customized_view, parent,false);
holder = new ViewHolder();
holder.rg=(RadioGroup)view.findViewById(R.id.radioGroup_option);
holder.tv_qstn=(TextView)view.findViewById(R.id.tv_id);
holder.rb_opt1=(RadioButton)view.findViewById(R.id.rb_1);
holder.rb_opt2=(RadioButton)view.findViewById(R.id.rb_2);
view.setTag(mQuestion);
}else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
Question qstnRef=mQuestion.get(position);
holder.tv_qstn.setText(qstnRef.getQstn());
holder.rb_opt1.setText(qstnRef.getOpt1());
holder.rb_opt2.setText(qstnRef.getOpt2());
holder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
//List<Question> data =(List<Question>) group.getTag();
//Toast.makeText(context,(CharSequence) data.get(checkedId).getOpt2(),Toast.LENGTH_SHORT).show();
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
RadioButton r_btn=(RadioButton)group.getChildAt(i);
if (r_btn.getId() == checkedId){
System.out.println(r_btn.getText().toString());
}
}
}
});
return view;
}
private class ViewHolder {
public TextView tv_qstn;
public RadioButton rb_opt1,rb_opt2;
public RadioGroup rg;
}
}
But i am trying to get this data that i enter in the UI, but I am not able to get this to work, please provide me assistance !!!!
The code in the current format is giving me runtime error :-
05-09 06:01:06.669: E/AndroidRuntime(2420):
java.lang.ClassCastException: android.widget.TextView cannot be cast
to android.widget.RadioButton
05-09 06:01:06.669: E/AndroidRuntime(2420): at
com.example.customadapter.MyAdapter$1.onCheckedChanged(MyAdapter.java:83)
group.getChildCount() returns 3 as it has 3 child. but 1 child is of TextView that's why you were getting java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.RadioButton
To avoid it do type checking using instanceof before typecasting.
do like this:
int childCount=group.getChildCount();
for (int i=0;i<childCount;i++){
if(group.getChildAt(i) instanceof RadioButton ) { // check if child is `RadioButton`
RadioButton r_btn = (RadioButton) group.getChildAt(i);
if (r_btn.getId() == checkedId) {
System.out.println(r_btn.getText().toString());
}
}
}
I could not frame a proper question but here is what I am facing. I have a ListActvity and here's the code:
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class dbMainactivty extends ListActivity {
// Declare Variables
public static final String ROW_ID = "row_id";
private static final String TITLE = "title";
private ListView noteListView;
private CursorAdapter noteAdapter;
private TextView text;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t.setScreenName("dbMainactivty");
t.send(new HitBuilders.AppViewBuilder().build());
// Locate ListView
noteListView = getListView();
// setContentView(R.layout.list_note);
//noteListView = (ListView) findViewById(R.id.listview);
setContentView(R.layout.dbmainactivitylayout);
text = (TextView) findViewById(R.id.mainText);
// Prepare ListView Item Click Listener
noteListView.setOnItemClickListener(viewNoteListener);
// Map all the titles into the ViewTitleNotes TextView
String[] from = new String[] { TITLE };
int[] to = new int[] { R.id.ViewTitleNotes };
// Create a SimpleCursorAdapter
noteAdapter = new SimpleCursorAdapter(dbMainactivty.this,
R.layout.list_note, null, from, to);
// Set the Adapter into SimpleCursorAdapter
setListAdapter(noteAdapter);
}
// Capture ListView item click
OnItemClickListener viewNoteListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// Open ViewNote activity
Intent viewnote = new Intent(dbMainactivty.this, ViewNote.class);
// Pass the ROW_ID to ViewNote activity
viewnote.putExtra(ROW_ID, arg3);
startActivity(viewnote);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
};
#Override
protected void onResume() {
super.onResume();
// Execute GetNotes Asynctask on return to MainActivity
new GetNotes().execute((Object[]) null);
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
}
#Override
protected void onStop() {
Cursor cursor = noteAdapter.getCursor();
// Deactivates the Cursor
if (cursor != null)
cursor.deactivate();
noteAdapter.changeCursor(null);
super.onStop();
GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStop(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, menu);
//return true;
return super.onCreateOptionsMenu(menu);
}
//#Override
//public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
//
// if (drawerListener.onOptionsItemSelected(item)) {
// return true;
// }
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
// Intent ia = new Intent(Intent.ACTION_VIEW);
// ia.setData(Uri.parse("market://details?id=" + getApplicationContext().getPackageName()));
// startActivity(i);
//break;
String webpage = "http://developer.android.com/index.html";
Intent intent2 = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent2);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Tracker t = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t.send(new HitBuilders.EventBuilder()
.setCategory("rate CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "");
i.setType("text/plain");
startActivity(i);
Tracker t1 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t1.send(new HitBuilders.EventBuilder()
.setCategory("share CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
return true;
case R.id.action_maila:
Intent imail = new Intent(Intent.ACTION_SEND);
imail.setType("message/rfc822");
imail.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
imail.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
imail.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(imail, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(dbMainactivty.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Tracker t2 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t2.send(new HitBuilders.EventBuilder()
.setCategory("Mail CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
break;
case R.id.action_home:
Intent ihome = new Intent(this, MainActivity.class);
startActivity(ihome);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
Tracker t3 = ((AnalyticsSampleApp)this.getApplication()).getTracker(TrackerName.APP_TRACKER);
t3.send(new HitBuilders.EventBuilder()
.setCategory("GoToHome CategoryListActivity") // category i.e. Player Buttons
.setAction("Button") // action i.e. Play
.setLabel("clicked") // label i.e. any meta-data
.build());
return true;
}
return super.onOptionsItemSelected(item);
};
// GetNotes AsyncTask
private class GetNotes extends AsyncTask<Object, Object, Cursor> {
DatabaseConnector dbConnector = new DatabaseConnector(dbMainactivty.this);
#Override
protected Cursor doInBackground(Object... params) {
// Open the database
dbConnector.open();
return dbConnector.ListAllNotes("maincat LIKE 'quiz' AND subcat LIKE 'test'");
}
#Override
protected void onPostExecute(Cursor result) {
noteAdapter.changeCursor(result);
// Close Database
Cursor cursor = noteAdapter.getCursor();
if(cursor != null && cursor.getCount() > 0){
cursor.moveToFirst();
//do your action
//Fetch your data
// GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
//Toast.makeText(getBaseContext(), "Yipeee!", Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(getBaseContext(), "No records yet!", Toast.LENGTH_SHORT).show();
Toast toast = Toast.makeText(dbMainactivty.this, "No records yet!", Toast.LENGTH_SHORT);
toast.show();
toast.setGravity(Gravity.CENTER, 0, 0);
finish();
}
dbConnector.close();
}
}
#Override
protected void onStart() {
super.onStart();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Please check your Internet Connection.")
.setTitle("")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {GoogleAnalytics.getInstance(dbMainactivty.this).reportActivityStart(this);
}
}
}
Now the layout file for this is list_note.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.96"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/ViewTitleNotes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_margin="20dp"
android:textColor="#000000"
android:textStyle="bold"
android:focusable="false"
android:focusableInTouchMode="false"
/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
When I implement above code every thing works fine. However, I want to include some other data so i am calling another layout file which includes additional data:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/mainText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Pinned Questions" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:background="#FFFFFF"
/>
<TextView
android:id="#android:id/empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mainText"
android:text="There is no data"
android:textStyle="bold" />
</RelativeLayout>
When I include this layout the list shows up but nothing happens when I click on list item. The normal working would be when I click list item it should open the next activity with desired clicked item.
Thanks in advance.
Well I would suggest You To Implement View.OnItemClickListener() and then use
noteListView.setOnItemClickListener(this);
This will work perfectly.
Hope I Helped.
How do I get the line in sync with the round ball images and how to change the text and image when clicked ?
I'd like to do something like this:
https://www.behance.net/gallery/13564677/Blog
I got the ListView but I just need help in building the straight line pass through the round ball images.
Thanks for your help!
My Code Follows:
My activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d3d3d3"
>
<FrameLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
</FrameLayout>
<ListView
android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:divider="#null"
android:layout_gravity="left"
android:background="#A55676"
>
</ListView>
</android.support.v4.widget.DrawerLayout>
custom_row.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="horizontal"
android:paddingLeft="35dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:orientation="horizontal"
android:background="#drawable/border"
>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="-5sp"
android:paddingTop="30dp"
/>
<TextView
android:id="#+id/textView1"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="25dp"
android:drawablePadding="20dp"
android:paddingLeft="3dp"
android:paddingTop="25dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ffffff" />
</LinearLayout>
</LinearLayout>
MainActivity.java
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnItemClickListener {
private DrawerLayout drawerLayout;
private ListView listview;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview=(ListView) findViewById(R.id.drawerList);
drawerLayout=(DrawerLayout)findViewById(R.id.drawerlayout);
MyAdapter myAdapter = new MyAdapter(this);
listview.setAdapter(myAdapter);
drawerLayout.setDrawerShadow(R.drawable.navbar_shadow, Gravity.LEFT);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer,R.string.drawer_open, R.string.drawer_close)
{
#Override
public void onDrawerClosed(View drawerView)
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Drawer Closed", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this,"Drawer Opened", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setIcon(R.color.transparent);
listview.setOnItemClickListener(this);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerListener.onConfigurationChanged(newConfig);
}
public void selectItem(int position)
{// TODO Auto-generated method stub
listview.setItemChecked(position, true);
//setTitle(planets[position]);
}
public void setTitle(String title)
{
getActionBar().setTitle(title);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if(drawerListener.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{ // TODO Auto-generated method stub
ImageView titleImageView = (ImageView)view.findViewById(R.id.imageView1);
TextView titleTextView = (TextView)view.findViewById(R.id.textView1);
switch(position)
{
case 0:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState()){
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 1:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 2:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 3:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
Intent intent = new Intent(getApplicationContext(),Featured.class);
startActivity(intent);
break;
case 4:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
case 5:
if (titleImageView.getDrawable().getConstantState() == getResources().getDrawable( R.drawable.ic_new).getConstantState())
{
titleImageView.setImageResource(R.drawable.ic_new1);
titleTextView.setTypeface(Typeface.DEFAULT_BOLD);
}
else
{
titleImageView.setImageResource(R.drawable.ic_new);
titleTextView.setTextAppearance(getApplicationContext(), R.style.normalText);
}
break;
default:
break;
}
}
}
class MyAdapter extends BaseAdapter
{
String[] socialSites;
int [] images = {R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new,R.drawable.ic_new};
Context context;
public MyAdapter(Context context) {
// TODO Auto-generated constructor stub
this.context=context;
socialSites = context.getResources().getStringArray(R.array.social);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return socialSites.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return socialSites[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = null;
if(convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_row,parent, false);
}
else
{
row=convertView;
}
TextView titleTextView = (TextView) row.findViewById(R.id.textView1);
ImageView titleImageView = (ImageView) row.findViewById(R.id.imageView1);
titleTextView.setText(socialSites[position]);
titleImageView.setImageResource(images[position]);
return row;
}
}
Use a ListView, and assign a 9-patch drawable to each item's background which will consist of a centered dot and the vertical line.
The whole trick will be to specify the strechable regions of your nine-patch properly (stretch the line and not the dot).
Once you are happy with that, just make a different dot appearance for the active element and use an XML selector drawable to assign either the default or activated state 9 patch to the background.
i'va already read all answers related with these questions and I'm sure none solves my problem, I'm getting crazy with this error, please any help would be appreciated
<LinearLayout 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:padding="5dip"
android:orientation="vertical" >
<TextView android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/title_scaned_value"/>
<TextView
android:id="#+id/scanedFormat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/title_scaned_value_empty"/>
<TextView
android:id="#+id/scanedValue"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/title_scaned_value_empty"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/title_scan"
android:onClick="commandScan"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="productes"
android:onClick="productes"/>
My activity related with this layout works fine, but when i click a button to start another activity this error appears.
I'm workin with Zxing library and here's my CaptureActivity:
package org.example.sherlock_;
import org.example.sherlock_.helpers.ExceptionHelper;
import android.content.Intent;
import android.graphics.Bitmap;
import com.google.zxing.Result;
import com.google.zxing.client.android.result.ResultHandler;
public class CaptureActivity extends com.google.zxing.client.android.CaptureActivity {
#Override
public void handleDecodeInternally(Result rawResult, ResultHandler resultHandler, Bitmap barcode) {
//super.handleDecodeInternally(rawResult, resultHandler, barcode);
try {
Intent resultIntent = new Intent();
resultIntent.putExtra(com.google.zxing.client.android.Intents.Scan.RESULT_FORMAT, rawResult.getBarcodeFormat().toString());
resultIntent.putExtra(com.google.zxing.client.android.Intents.Scan.RESULT, resultHandler.getDisplayContents());
setResult(RESULT_OK, resultIntent);
finish();
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
}
I post my MainActivity too because I'm going really mad :)
package org.example.sherlock_;
import org.example.sherlock_.helpers.ExceptionHelper;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainActivity extends SherlockActivity {
private TextView scanedValue;
private TextView scanedFormat;
private final static int SCAN_CODE_REQUEST_CODE = 123456;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scanedValue = (TextView)findViewById(R.id.scanedValue);
scanedFormat = (TextView)findViewById(R.id.scanedFormat);
}
#Override
protected void onActivityResult(int pRequestCode, int pResultCode, Intent pData) {
try {
if (pRequestCode == SCAN_CODE_REQUEST_CODE) {
if (pResultCode == RESULT_OK) {
String result = pData.getStringExtra
(com.google.zxing.client.android.Intents.Scan.RESULT);
String format = pData.getStringExtra
(com.google.zxing.client.android.Intents.Scan.RESULT_FORMAT);
if (scanedValue != null) {
if (result != null &&
!result.trim().equals("")) {
scanedValue.setText(result);
//if(db != null){
//String valor= result ;
//}
} else {
scanedValue.setText(getString(R.string.title_scaned_value_empty));
}
}
if (scanedFormat != null) {
if (format != null &&
!format.trim().equals("")) {
scanedFormat.setText(format);
//if(db != null){
//String tipus = format;
//}
} else {
scanedFormat.setText(getString(R.string.title_scaned_value_empty));
}
}
} else {
if (scanedValue != null)
scanedValue.setText(getString(R.string.title_scaned_value_empty));
if (scanedFormat != null)
scanedFormat.setText(getString(R.string.title_scaned_value_empty));
}
}
//Insertamos los datos en la tabla Usuarios
// db.execSQL("INSERT INTO Productes (codi, tipus, valor) " +
// "VALUES (" + i + ", '" + tipus +"', '"+ valor +"')");
// db.close();
//i+=i;
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
public void commandScan(View pView) {
try {
Intent captureIntent = new Intent(this, CaptureActivity.class);
captureIntent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(captureIntent, SCAN_CODE_REQUEST_CODE);
} catch (Exception e) {
ExceptionHelper.manage(this, e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_settings) {
Toast.makeText(this, "configuración pulsado"
, Toast.LENGTH_SHORT).show();
}
return true;
}
}