When I go to run the app everything seems fine but when I press the Start Button it doesnt display Hello I even tried to set text before the thread and it still didnt work. Why would this be happening?
Here is the code:
public class MainActivity extends Activity implements OnClickListener {
Handler mHandler;
Button enter;
Button start;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enter = (Button)findViewById(R.id.enter);
start = (Button)findViewById(R.id.start);
display =(TextView)findViewById(R.id.Display);
mHandler = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Bundle bundle = msg.getData();
String string = bundle.getString("myKey");
display.setText(string);
}
};
}
#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 void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.enter:
break;
case R.id.start:
Thread setText = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
Message msg= Message.obtain();
Bundle bundle = new Bundle();
String dateString;
dateString = "Hello";
bundle.putString("myKey", dateString);
msg.setData(bundle);
mHandler.sendMessage(msg);
}
};
setText.start();
break;
}
}
}
You didn't register Listeners on your enter/start button in the onCreate() method. Just call f.e.:
enter.setOnClickListener(this);
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class MainActivity extends Activity {
Button button = (Button)findViewById(R.id.btn);
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateHandler.post(updateThread);
}
});
}
#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);
}
Handler updateHandler = new Handler(){
public void handleMessage(Message msg) {
bar.setProgress(msg.arg1);
updateHandler.post(updateThread);
};
};
Runnable updateThread = new Runnable() {
int i = 0;
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("------------");
i = i+10;
Message msg = updateHandler.obtainMessage();
msg.arg1 = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateHandler.sendMessage(msg);
if (i==100) {
updateHandler.removeCallbacks(updateThread);
}
}
};
}
Logcat:
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.zxy.handlerpbtest/com.zxy.handlerpbtest.MainActivity}: java.lang.NullPointerException
You can rewrite this code of lines:
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
Button button = (Button)findViewById(R.id.btn);
As:
public class MainActivity extends Activity {
Button button ;
ProgressBar bar ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar = (ProgressBar)findViewById(R.id.pbar);
button = (Button)findViewById(R.id.btn);
.....
}}
Then you will not get null pointer exception.
This line
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
Button button = (Button)findViewById(R.id.btn);
should be in your onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar bar = (ProgressBar)findViewById(R.id.pbar);
Button button = (Button)findViewById(R.id.btn);
}
Here is Complete Solution :
public class MainActivity extends Activity {
Button button;
ProgressBar bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
button = (Button) findViewById(R.id.btn);
bar = (ProgressBar) findViewById(R.id.pbar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
updateHandler.post(updateThread);
}
});
}
Handler updateHandler = new Handler() {
public void handleMessage(Message msg) {
bar.setProgress(msg.arg1);
updateHandler.post(updateThread);
}
};
Runnable updateThread = new Runnable() {
int i = 0;
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("------------");
i = i + 10;
Message msg = updateHandler.obtainMessage();
msg.arg1 = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updateHandler.sendMessage(msg);
if (i == 100) {
updateHandler.removeCallbacks(updateThread);
}
}
};
}
This is my Profile.java file in which i want to add the code for "item 1" that when it was clicked it must associate with my custom.java file.
package com.haider.first;
public class Profile
extends ListActivity
implements OnItemLongClickListener {
Activity activity;
//on create method
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
//Registering list for context menu
activity = this;
ListView lv = (ListView) findViewById(android.R.id.list);
registerForContextMenu(lv);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.profile)));
}
//this is code for create context menu
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
// this is code for selecting context item to perform desired actions
#Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()) {
case R.id.item1:
// Here i need code from which after click custom.java will be selected or choosen
case R.id.item2:
startActivity(new Intent(Profile.this, Custom.class));
return true;
default:
return super.onContextItemSelected(item);
}
}
//This is code for Enable Single CLick while opening Context Menu
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
activity.openContextMenu(l);
super.onListItemClick(l, v, position, id);
}
//This code disbale long click
#Override
public boolean onItemLongClick(AdapterView<?> enter code here parent, View view, int position, long id) {
// TODO Auto-generated method stub
activity.closeContextMenu();
return false;
}
}
code for custom.java file in which all settings are implemented
public class Custom
extends Activity {
private SeekBar mediaVlmSeekBar = null;
private AudioManager audioManager = null;
//Oncreate Method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.custom_sett);
initControls();
// Code for vibration but my app vibrates after short time intervals even it is closed
ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton1);
tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//this method is for changing status of mutiple options.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked) {
Intent vibintent = new Intent(getApplicationContext(), Vibration.class);
startService(vibintent);
} else {
}
}
});
//Code for Controlling Volume, here i am facing issue that i cannot change volume of my app with device buttons
/Here is my code for Volume
private void initControls () {
// TODO Auto-generated method stub
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mediaVlmSeekBar = (SeekBar) findViewById(R.id.seekBar1);
mediaVlmSeekBar.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
//Set the progress with current Media Volume
mediaVlmSeekBar.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
try {
mediaVlmSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
..........
Now my problem is when user will select item 1 named "General" it would select custom.java file without opening. In other words , when user select General the whole settings for volume, vibration, ringtone etc will be automatically selected.
I am trying to save to shared preferences. I want to be able to load from shared preferences but when I save and or load at the moment my app crashes.
I also want to be able to have my handler/runnable resume when my app starts up. How can I do this?
Here is my code:
public class MainActivity extends ActionBarActivity {
public void save(){
Editor editor = pref.edit();
editor.putInt("countertest", counter);
editor.commit();
}//end of save
public void read(){
counter = pref.getInt("countertest", counter);
}//end of read
Handler testHandler = new Handler();
int counter;
TextView testView;
Button testButton;
Runnable Runnable0;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testView = (TextView) findViewById(R.id.testView);
testButton = (Button) this.findViewById(R.id.testButton);
// read();
testView.setText(Integer.toString(counter));
}
#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 onResume() {
//read();
final Runnable Runnable0 = new Runnable() {
#Override
public void run() {
counter += 1;
testView.setText(Integer.toString(counter));
testHandler.postDelayed(this, 1000);
// save();
}// end of if
};
/* button click */
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Start runnable */
testButton.setEnabled(false);
counter -= 5;
//save();
testView.setText(Integer.toString(counter));
testHandler.post(Runnable0);
}// end of onClick
});// end of blingButton onClickListener
super.onResume();
}//end of onResume
#Override
protected void onPause() {
//save();
testHandler.removeCallbacks(Runnable0);
super.onPause();
}//end of onPause
}
You haven't initialize your pref object. You have just declared it. So you need to do it on onCreate() by
pref = getSharedPreferences("MySP", 0);
OR
pref = PreferenceManager.getDefaultSharedPreferences(this);
I’m using ksoap to call a web service.
When Application starts or when i scroll to end of page Application fetches data from Web Service correctly and it shows data as well as i want, But When I want to show Progress Dialog in a AsyncTask it doesn’t work correctly. It shows Progress Dialog after PostExecute in a blik of eyes. So, What's wrong in my code ? I can't understand where is my problem. ;-)
I have a web service class called ElvatraWebService:
Here is a Method witch is fetch latest post with Asynctasks
private String GetLastPublicPosts(int counter){
...
...
...
...
return resTxt; //Returns JSON String
}
public String getLatestPost(int counter, Activity a){
CallLatestPost task = new CallLatestPost(counter,a);
try {
strJSON = task.execute("getLatest").get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Log.i("sss", "--" + strJSON);
return strJSON;
}
private class CallLatestPost extends AsyncTask<String, Void, String> {
private int Counter = 0;
private ProgressDialog dialog;
private Activity activity;
private Context context;
public CallLatestPost (int c,Activity actt) {
super();
this.Counter = c;
activity = actt;
context = actt;
dialog = new ProgressDialog(this.context);
}
#Override
protected String doInBackground(String... params) {
ElvatraWebService elws = new ElvatraWebService();
String tmp = elws.GetLastPublicPosts(this.Counter);
//Log.i("strJSON",strJSON);
return tmp;
}
#Override
protected void onPostExecute(String result) {
//Set response
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Connecting...");
//dialog.setIndeterminate(true);
dialog.setCancelable(true);
dialog.show();
Log.i("###Async", "=== " + "PreExec");
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
I have a Class called post. It will call getLatestPost from Elvatrawebservice.
Then it will convert JSON String to JsonArray with PostAdapter class. PostAdapter is a class extends BaseAdapter.
In Main Activity I call a local Method called LoadContent in onCreate method.
Here is MainActivity Class
public class MainActivity extends Activity {
String displayText="";
public TextView tv;
public ListView lv;
public ProgressBar pg;
int theCounter=20;
String[] strTAG = new String[] {"title","photo","date","desc","linkurl"};
//int[] intField = new int[] {R.id.title,R.id.imgPost, R.id.Date, R.id.desc, R.id.link};
ListAdapter sa;
List<HashMap<String,Object>> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recentposts);
lv = (ListView) findViewById(R.id.list);
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
final int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount) {
//load more data
// Load content of listview
LoadContent();
}
}
});
}
#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 void onDestroy() {
super.onDestroy(); // Always call the superclass
// Stop method tracing that the activity started during onCreate()
android.os.Debug.stopMethodTracing();
}
public void LoadContent(){
lv = (ListView) findViewById(R.id.list);
Post p = new Post(theCounter);
theCounter+=20;
if (p.GetLatestPosts(lv,MainActivity.this))
{
//tv.setText("true");
}
}
}
You have
task.execute("getLatest").get();
You should not call get() as this blocks the ui thread waiting for the result making it asynctask asynchronous no more. Just use
task.execute("getLatest");
You can return result in doInBackground and update ui in onPostExecute.
I'm newbee on the android programming then I have a problem to integrate a part of code.
public class HomeActivity extends SherlockFragmentActivity
implements ActionBar.OnNavigationListener, VideoListFragment.OnVideoSelectedListener{
// create object of ActionBar and VideoListFragment
ActionBar actionbar;
VideoListFragment videoListFrag;
int selectedItem;
private AdController ad;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// add channel list array to actionbar spinner
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.channel_name, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
// remove actionbar title and add spinner to actionbar
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
}
// create option menu
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.home, menu);
return true;
}
// listener for option menu
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuShare:
// share google play link of this app to other app such as email, facebook, etc
Intent iShare = new Intent(Intent.ACTION_SEND);
iShare.setType("text/plain");
iShare.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.subject));
iShare.putExtra(Intent.EXTRA_TEXT, getString(R.string.message)+" "+getString(R.string.gplay_web_url));
startActivity(Intent.createChooser(iShare, getString(R.string.share_via)));
return true;
case R.id.menuRate:
// open google play app to ask user to rate & review this app
Intent iRate = new Intent(Intent.ACTION_VIEW);
iRate.setData(Uri.parse(getString(R.string.gplay_url)));
startActivity(iRate);
return true;
case R.id.menuAbout:
// open About app page
Intent iAbout = new Intent(this, AboutActivity.class);
startActivity(iAbout);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
selectedItem = itemPosition;
// create object of VideoListFragment and send data position to that fragment
videoListFrag = new VideoListFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", itemPosition);
videoListFrag.setArguments(bundle);
// call video list fragment with new data
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, videoListFrag, "VIDEO_LIST_FRAGMENT")
.commit();
return true;
}
#Override
public void onVideoSelected(String ID) {
// TODO Auto-generated method stub
// call player page to play selected video
Intent i = new Intent(this, PlayerActivity.class);
i.putExtra("id", ID);
startActivity(i);
}
#Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_home);
ad = new AdController(this, "MY_LB_SECTION_ID");
ad.loadStartAd("MY_LB_AUDIO_ID", "MY_LB_REENGAGEMENT_ID");
AppTracker.startSession(this, "APPFIREWORKS_API_KEY");
}
#Override
public void onPause() { super.onPause();
if(ad != null) { ad.destroyAd();
} if(!isFinishing()) { AppTracker.pause(getApplicationContext());
} }
#Override
public void onResume() { super.onResume();
AppTracker.resume(getApplicationContext());
}
#Override
public void onDestroy() { super.onDestroy();
if(ad != null) { ad.destroyAd();
} AppTracker.closeSession(getApplicationContext(),true);
}
}
The problem is on on create.
Sorry for my bad english.
Thanks for your response.
Regards
You have 2 onCreate functions in the same Activity. You can only have one. That's why its complaining that there is already a method with same signature. Delete one of them and move the stuff from one to other. As mentioned by #Ravn in comments, you can have multiple functions with same name but ofcourse with different arguments.
You cannot have method with same signature twice
#Override
public void onCreate(Bundle savedInstanceState)
#Override
public void onCreate(Bundle b)