Intent is not working on click event - java

Hy experts.
i am new to android, i am trying to generate an intent to go on next activity, i am using listview, when i click on list item, it should go to that class which item item is clicked.
here is my code.
package com.example.data_server_assi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Menu extends ListActivity{
String[] menu = {"AddInfo","DataBaseInfo"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(Menu.this, android.R.layout.simple_list_item_1, menu));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
try {
Toast.makeText(Menu.this, "Test" ,Toast.LENGTH_SHORT).show();
Class menuItem = Class.forName("com.example.data_server_assi."+menu[position]);
Intent menuIntent = new Intent(Menu.this,menuItem);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`

Put below code, You have missed one line of code:
Intent menuIntent = new Intent(Menu.this,menuItem);
startActivity(menuIntent);
OR
startActivity(new Intent(menu.this,menuItem));

You have missed starting your activity by-
startActivity(YOUR_INTENT_NAME);

Related

Is there a way to change android.R.layout.simple_list_item_1, to my custom layout?

part of the code
package com.example.pass;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class Permission extends ActionBarActivity implements OnClickListener, OnKeyListener{
EditText Date;
EditText Time;
EditText userName;
EditText userSurname;
Button btnOK;
Button Cancel;
EditText Name;
String Surname;
Button clear;
ListView list;
ArrayList<String> Items;
ArrayAdapter<String> aa;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_permission);
list = (ListView)findViewById(R.id.listView1);
Items = new ArrayList<String>();
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Items);
list.setAdapter(aa);
// Include dialog.xml file
// Set dialog title
final Dialog dialog = new Dialog(Permission.this);
dialog.setContentView(R.layout.dialog_permission);
dialog.setTitle("Custom Dialog");
clear = (Button)findViewById(R.id.clear);
Button add = (Button) findViewById(R.id.add);
// Create custom dialog object
// set values for custom dialog components - text, image and button
userName = (EditText) dialog.findViewById(R.id.dialog_username);
userSurname = (EditText)dialog.findViewById(R.id.dialog_usersurname);
Time = (EditText)dialog.findViewById(R.id.dialog_time2);
Date = (EditText)dialog.findViewById(R.id.dialog_date2);
btnOK = (Button) dialog.findViewById(R.id.OK);
Cancel = (Button) dialog.findViewById(R.id.Cancel);
btnOK.setOnClickListener(this);
userName.setOnKeyListener(this);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentDate=Calendar.getInstance();
int mYear = mcurrentDate.get(Calendar.YEAR);
int mMonth = mcurrentDate.get(Calendar.MONTH);
int mDay = mcurrentDate.get(Calendar.DAY_OF_MONTH);
DatePickerDialog mDatePicker=new DatePickerDialog(Permission.this, new OnDateSetListener() {
public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday) {
// TODO Auto-generated method stub
/* Your code to get date and time */
Date.setText(selectedyear+"-"+(selectedmonth+1)+"-"+selectedday);
}
},mYear, mMonth, mDay);
mDatePicker.setTitle("Select date");
mDatePicker.show(); }
});
Time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
Calendar mcurrentTime=Calendar.getInstance();
int mHour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int mMinute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker=new TimePickerDialog(Permission.this, new OnTimeSetListener() {
public void onTimeSet(TimePicker timepicker, int selectedhour, int selectedminute ) {
// TODO Auto-generated method stub
/* Your code to get date and time */
if (selectedminute<10){
Time.setText(selectedhour+":"+"0"+(selectedminute)+""+"val");
}
else
Time.setText(selectedhour+":"+(selectedminute));
}
},mHour, mMinute, false);
mTimePicker.setTitle("Select date");
mTimePicker.show(); }
});
Cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//To show current date in the datepicker
dialog.dismiss();
}
});
// OK.setOnClickListener(new OnClickListener() {
/* #Override
public void onClick(View v) {
// TODO Auto-generated method stub
this.addItem(this.userName.getText().toString());
//CONVERTING THE TEXT IN TO STRING...
System.out.println(Name);
}
});*/
clear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
dialog.show();
}
});
}
private void addItem(String item){
if(item.length()>0){
this.Items.add(item);
this.aa.notifyDataSetChanged();
this.userName.setText("");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.permission, 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 boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(event.getAction()==KeyEvent.ACTION_DOWN&&keyCode==KeyEvent.KEYCODE_DPAD_CENTER){
this.addItem(this.userName.getText().toString());
this.addItem(this.userSurname.getText().toString());
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v == this.btnOK){
this.addItem(this.userName.getText().toString());
this.addItem(this.userSurname.getText().toString());
}
}
}
Everytime i try to change to custom layout everything crashes, i dont know how to do it not losing dialog window, because text i am reading from is in my custom dialog. I know that maybe creating new adapter class can solve the problem but i want to try another way.
Use CTRL + Left click on android.R.layout.simple_list_item_1 to open it.
Copy the contents to your own XML layout file, and edit it as your wish.
Change
android.R.layout.simple_list_item_1
To
R.layout.your_layout

Error in NSD Network Service Discovery in android

I don't know whats going wrong with my app i followed so many tutorials, any hint/help/advise would be appreciated, I am new on android. i am getting error as in onserviceregistrationfailed function of listner.
package com.example.ravinetworkapplication;
import java.io.IOException;
import java.net.ServerSocket;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.pm.ServiceInfo;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
NsdManager mNsdManager;
Context context;
NsdManager.DiscoveryListener mDiscoveryListner=null;
NsdManager.RegistrationListener mRegistrationListener=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mNsdManager= (NsdManager) this.getSystemService(Context.NSD_SERVICE);
final ServerSocket mServerSocket;
final ArrayList<String> listName = new ArrayList<String>();
Integer localPort = 0;
final ListView list = (ListView) findViewById(R.id.listView1);
listName.add("arunima");
listName.add("abhishek");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1,listName);
list.setAdapter(adapter);
try {
mServerSocket = new ServerSocket(0);
localPort = mServerSocket.getLocalPort();
mServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
}
#Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
Log.v("service registrd", "i am on folks");
Toast.makeText(getApplicationContext(), "Registerd", Toast.LENGTH_LONG).show();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
Log.v("service registration fail", "can not register service kumar ravi");
}
};
mDiscoveryListner = new NsdManager.DiscoveryListener() {
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("cannot stop service", "service discovery failed");
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("can not start", "Can not start discovery kumar ravi "+errorCode);
}
#Override
public void onServiceLost(NsdServiceInfo service) {
// TODO Auto-generated method stub
}
#Override
public void onServiceFound(NsdServiceInfo service) {
// TODO Auto-generated method stub
Log.v("service found", "we found the service");
if(!service.getServiceType().equals("_myapp.tcp.")){
}
else if(service.getServiceName().equals("kumar")){
}
else {
listName.add(service.getServiceName());
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "Finally found the service "+service.getServiceName(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
// TODO Auto-generated method stub
}
#Override
public void onDiscoveryStarted(String serviceType) {
// TODO Auto-generated method stub
Log.v("Service Discovery Started", "Searching of Service Discovery");
}
};
Log.v("registerd port", localPort.toString());
final NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(localPort);
serviceInfo.setServiceName("kumar");
serviceInfo.setServiceType("_myapp.tcp.");
//mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
Button startBroadcast = (Button) findViewById(R.id.button1);
Button startListen = (Button) findViewById(R.id.button2);
startBroadcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
});
startListen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.discoverServices("_myapp.tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListner);
}
});
}
#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
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListner);
Log.v("Stopped", "Scanning stopped"); }
catch(Exception e){
Log.v("some error in unregistring service", e.toString());
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}

Button and menus stop working after orientation change

I have an Android app which uses tabs and fragments for navigation. The app works fine when launched, but after I change the orientation the menu items and the widgets in the fragments stop working. The app works if I put
android:configChanges="orientation|screenSize"
in the manifest, but in the Android documentation it says that this should be a last resort, so I'm wondering if there is a better solution. Here's the code for the host activity and one of the fragments.
package com.mynews;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//stopService(new Intent(this, FindArticlesService.class));
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar.newTab()
.setText("Articles")
.setTabListener(new TabListener<Articles>(this, "articles", Articles.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Websites")
.setTabListener(new TabListener<UserSites>(this, "websites", UserSites.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Add a website")
.setTabListener(new TabListener<AddSites>(this, "add a site", AddSites.class));
actionBar.addTab(tab);
}
#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
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
////Intent intent = new Intent(this, FindArticlesService.class);
//this.startService(intent);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
Fragment fragment;
final Activity activity;
final String tag;
final Class<T> mClass;
public TabListener(Activity a, String s, Class<T> c){
activity = a;
tag = s;
mClass = c;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment == null){
fragment = Fragment.instantiate(activity, mClass.getName());
ft.add(android.R.id.content, fragment, tag);
}else{
ft.attach(fragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment != null){
ft.detach(fragment);
}
activity.closeContextMenu();
}
}
}
My Fragment Class
package com.mynews;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddSites extends Fragment {
public AddSites(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_add_sites);
// Show the Up button in the action bar.
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.add);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
UserSitesFunc usf = new UserSitesFunc(); //create a new UserSitesFunc to hold
try{ //the list of sites
FileInputStream fis = getActivity().openFileInput("MySites.ser");//check if there's a file
ObjectInputStream ois = new ObjectInputStream(fis);//with a USF object
usf = (UserSitesFunc) ois.readObject(); //if there is, deserialize it and use it
ois.close();//instead of a brand new object
}catch(IOException e){ //catch various exceptions
e.printStackTrace();
}catch(Exception ep){
ep.printStackTrace();
}finally{
try{ //do this with either the new object or the deserialised one
EditText website = (EditText) getActivity().findViewById(R.id.editText1);//get the input
EditText keywords = (EditText) getActivity().findViewById(R.id.editText2);//from the user
String web = website.getText().toString(); //store it in strings
String key = keywords.getText().toString();
String[] kwords = key.split(", ");
ArrayList<String> newKeywords = new ArrayList<String>();
for(String s:kwords){
newKeywords.add(s);
}
Sites s = new Sites(web, newKeywords);//create a new site from the input
if(usf.siteList.contains(s)){
showContainedDialog();
return;
}
usf.addSite(s);//add it to the user's list of sites
FileOutputStream fs = getActivity().openFileOutput("MySites.ser", Context.MODE_PRIVATE);//save it
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(usf);
oos.close();
Toast.makeText(getActivity(), web + " added to Tracked Websites", Toast.LENGTH_LONG).show();
website.setText("");
keywords.setText("");
}catch(MalformedURLException mue){
showDialog();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.activity_add_sites, container, false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.add_sites, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
return true;
}
return super.onOptionsItemSelected(item);
}
public static class NotAWebsiteDialog extends DialogFragment {
public static NotAWebsiteDialog newInstance(){
NotAWebsiteDialog notAWebsite = new NotAWebsiteDialog();
Bundle args = new Bundle();
notAWebsite.setArguments(args);
return notAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("Please enter a vaild web address")
.create();
}
}
public void showDialog(){
DialogFragment dialog = NotAWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Not A Website");
}
public static class AlreadyContainsWebsiteDialog extends DialogFragment {
public static AlreadyContainsWebsiteDialog newInstance(){
AlreadyContainsWebsiteDialog containsAWebsite = new AlreadyContainsWebsiteDialog();
Bundle args = new Bundle();
containsAWebsite.setArguments(args);
return containsAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("This website is already being tracked")
.create();
}
}
public void showContainedDialog(){
DialogFragment dialog = AlreadyContainsWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Contains this Website");
}
}
Kudos for not taking the easy way... keep up your programming efforts!
Refer to my answer here regarding the use of Menus and their host Fragments.

How do sent this data over to parse server using Android

I'm working on an app where whatevever the user speaks on the phone gets added to the listview(up to this is working fine) and on clicking that item on that list view,send that over to the parse server.
This is my class called Speech
`package com.example.projecta;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
public class Speech extends Activity implements OnClickListener {
ListView viewlist;
static final int check = 1111;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.speech);
Parse.initialize(this, "JnmLmnvOjxvRgBMGPl4XzOzvoqPPY7KGG2cqiExL", "8ejsJCanB26YYB6Io3jKov5wcwuajcB1zjRPUyMs");
ParseObject.registerSubclass(Storedata.class);
ParseAnalytics.trackAppOpened(getIntent());
viewlist = (ListView)findViewById(R.id.speechview);
Button b = (Button)findViewById(R.id.speechb);
b.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent in = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
in.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
in.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak Louder");
startActivityForResult(in, check);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == check && resultCode == RESULT_OK){
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
viewlist.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
}
super.onActivityResult(requestCode, resultCode, data);
}
public void createStoredata(View v) {
Storedata st = new Storedata();
st.setDescription(viewlist.toString());
st.saveEventually();
}
}
`
This is my store data class
package com.example.projecta;
import com.parse.ParseObject;
public class Storedata extends ParseObject{
public Storedata(){
}
public void setDescription(String description){
put("description", description);
}
{
}
}
I really need help with this thanks.
You need to add a listener to your listview itself to click the items
viewlist.setClickable(true);
viewlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
//perform action with your item
}
});

The value of a variable in one class is recieved as null in another when called in java

I want to use the value of a string variable in one class into another...
But when i do so by creating an object in the calling class of the called class, i get the value as null.
I tried searching on the net and stack overflow and went through some similar answers,but the solutions to them were specific to those questions.So m asking again.
here are the 2 classes -
1st one is the class from which i want to use the variable.
class is - SelectedClass variable i want to use in another class - SelectedClass( a string)
2nd class is FEa.I want to use the value of the variable "SelectedClass" from the 1st class.
CLASS 1(SelectedClass)-
package com.attendance_trial.nirmik;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SelectClass extends ListActivity
{
public String classes2[] = {"FEa","FEb","SEa","SEb"};
String SelectedClass;
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String SelectedClass = classes2[position];
try
{
Class MyClass = Class.forName("com.attendance_trial.nirmik." + SelectedClass);
Intent myintent = new Intent(SelectClass.this,MyClass);
startActivity(myintent);
}
catch(ClassNotFoundException cnf)
{
cnf.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
setListAdapter(new ArrayAdapter<String>(SelectClass.this, android.R.layout.simple_list_item_1, classes2));
}
}
CLASS 2 (FEa) -
package com.attendance_trial.nirmik;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FEa extends Activity implements View.OnClickListener
{
SelectClass sc = new SelectClass();
//Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,bSend;
Button bSend;
TextView tvDisp;
String acc="";
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fea);
initialise();
}
private void initialise()//initialise all buttons etc
{
bSend = (Button) findViewById (R.id.BtnSendMsg);
bSend.setOnClickListener(this);
tvDisp=(TextView) findViewById (R.id.TxtViewDisplay);
}
public void onButtonClick(View v)
{
// TODO Auto-generated method stub
Button theButton = (Button)v;
String chk = theButton.getText().toString();
if(chk.contentEquals("1")||chk.contentEquals("2")||chk.contentEquals("3")||chk.contentEquals("4")||chk.contentEquals("5")
||chk.contentEquals("6")||chk.contentEquals("7")||chk.contentEquals("8")||chk.contentEquals("9"))
{
acc = acc + "0" + chk;
}
else
{
acc = acc +chk;
}
tvDisp.setText("String Is:" + acc);
}//method end
#Override
public void onClick(View v2)
{
// TODO Auto-generated method stub
int retid = v2.getId();
if(retid == R.id.BtnSendMsg ) //send button clicked
{
String msg = sc.SelectedClass + "2210"+ acc;
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, msg);
startActivity(emailIntent);
}
}
}//main end
What you are doing is totally wrong.
You are not supposed to manually create objects from a class which extends an Activity. AKA you should never do this: SelectClass sc = new SelectClass();.
You have to tell the Android OS to do it for you by using:
Intent intent = new Intent(this, YourActivity.class);
startActivity(intent);
Now if you want to send a String from SelectClass to FEa, you can send it with the intent like this:
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra(EXTRA_MESSAGE_KEY, yourString);
startActivity(intent);
And in your second Activity, in onCreate():
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the string from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
}
You should check developer.android.com to make yourself an idea how to program in Android. Bare in mind, Android programming is not Java programming.
How to start a new Activity, from the developers site here.
Why don't you pass the values by using return ? That way you can call any function in any class and return the value to any other class.
More information on returning values or classes can be found here .

Categories