I got an while i am doing my code
My Error is :
Unable to instantiate activity ComponentInfo{com.example.example/com.example.sample.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.ApplicationInfo android.content.Context.getApplicationInfo()' on a null object reference
import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.jaredrummler.android.processes.AndroidProcesses;
import com.jaredrummler.android.processes.models.AndroidAppProcess;
import com.jaredrummler.android.processes.models.Stat;
import com.jaredrummler.android.processes.models.Statm;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class MainActivity extends AppCompatActivity {
List<RunningApplication> runningApplicationList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Button send = (Button) findViewById(R.id.button);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getRunningApps();
}
});
}
public void getRunningApps() {
List<AndroidAppProcess> processes = AndroidProcesses.getRunningAppProcesses();
PackageManager pm = getPackageManager();
for (AndroidAppProcess pro : processes) {
try {
String proccessname = pro.name;
Stat stat = pro.stat();
int pid = stat.getPid();
int parentProccessId = stat.ppid();
long startTime = stat.stime();
int policy = stat.policy();
char state = stat.state();
Statm statm = pro.statm();
long totalSizeofProccess = statm.getSize();
long residentSetSize = statm.getResidentSetSize();
PackageInfo packageInfo = pro.getPackageInfo(MainActivity.this,0);
//get the app name
String appName = packageInfo.applicationInfo.loadLabel(pm).toString();
//Get the app icon
Drawable appIcon = packageInfo.applicationInfo.loadIcon(pm);
//Add it to your list of running app
RunningApplication ra = new RunningApplication(appName,startTime,String.valueOf(pid),appIcon);
runningApplicationList.add(ra);
Log.e("APPNAME : ", appName);
} catch (Exception ex) {
Log.e("APPNAME.CONTEXT",ex.getMessage());
}
}
}
}```
You're getting NPE because you are trying to create a new instance of your button before calling setContentView(R.layout.activity_main);
This is what is causing your app to crash.
Consider changing your onCreate method to this snippet below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button send = (Button) findViewById(R.id.button);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getRunningApps();
}
});
}
Related
I am looking to find the first Install time of different applications installed on my device using my app.
The very basic PackageManager->PackageInfo->firstInstallTime field will suffice but it is always returning NameNotFoundException even though I have tried multiple app's(correct) package names.
package com.example.testingpackageinfo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.pm.PackageInfoCompat;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button button ;
TextView textView;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
button = findViewById(R.id.button);
textView = findViewById(R.id.textView);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PackageManager pm = context.getPackageManager();
PackageInfo pInfo = pm.getPackageInfo("com.google.android.youtube", 0);
long installTime = pInfo.firstInstallTime;
textView.setText(String.valueOf(installTime));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
textView.setText("Package Not found");
}
}
});
}
}
Try this :
private boolean checkInstalledApp(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
I am doing a saving system with sharedPreferences, the problem is that when I run the application it seems that if the String is saved but when converting it to int later it returns null values or 0...
the edit text only receives numbers, and what I try is to obtain its value as a string and then convert it to int, since I want to use that value in another activity
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView)findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
limiterStr = inputLimiter.getText().toString().trim();
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
public void Cargar(View view){
SharedPreferences limitPrefs= getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
if(!"".equals(recovaStr)) {
limiterInt = Integer.parseInt(recovaStr);
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
}
}
public void Guardar(View view){
if(mostrarLimite!=null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
}
}
}
NEW CODE!!!!********************************
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView) findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
Button btnCargarLimTEMP = findViewById(R.id.cargarTemp);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Guardar();
}
});
btnCargarLimTEMP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cargar();
}
});
}
private void Cargar() {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
try {
limiterInt = Integer.parseInt(recovaStr);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
Toast.makeText(this, "Limite de aciertos: " + limiterInt, Toast.LENGTH_SHORT).show();
}
private void Guardar() {
if (mostrarLimite != null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
limiterStr = inputLimiter.getText().toString().trim();
Toast.makeText(this, "Limite de aciertos actualizado: " + limiterStr, Toast.LENGTH_SHORT).show();
System.out.println(limiterStr);
}
}
}
I am trying to make a music application. So far I have been able to list the songs from a user's device and display them in a list. However, if a song is clicked to open the PlayerActivity, the activity crashes. Could someone assist me in playing the selected song from the song list? Improvements on the code would be highly appreciated.
The code below, MediaGalleryActivity.java gets the songs and passes them to specific intents:
package com.newton.hooked;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import com.newton.hooked.ui.main.SectionsPagerAdapter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MediaGalleryActivity extends AppCompatActivity {
public static final String SONGS_KEY = "SONGS";
public static final String ARTISTS_KEY = "ARTISTS";
public static final String ALBUMS_KEY = "ALBUMS";
ArrayList<String> songList = new ArrayList<>();
ArrayList<String> artistList = new ArrayList<>();
ArrayList<String> albumList = new ArrayList<>();
String[] song = new String[]{
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_media_gallery);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
int defaultValue = 0;
int page = getIntent().getIntExtra("Tab ID",defaultValue);
viewPager.setCurrentItem(page);
tabs.setupWithViewPager(viewPager);
Cursor audioCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,song,null,null,null);
ArrayList<AudioModel> audios = new ArrayList<>();
if(audioCursor != null){
if(audioCursor.moveToFirst()){
do{
int idColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
int titleColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
int artistColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
int albumColumn = audioCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
String thisTitle = audioCursor.getString(titleColumn);
String thisArtist = audioCursor.getString(artistColumn);
String thisAlbum = audioCursor.getString(albumColumn);
songList.add(thisTitle);
artistList.add(thisArtist);
albumList.add(thisAlbum);
} while (audioCursor.moveToNext());
}
}
audioCursor.close();
if(!songList.isEmpty()){
getIntent().putExtra(SONGS_KEY, songList);
} else {
getIntent().putExtra(SONGS_KEY,"No songs found");
}
if (!artistList.isEmpty()){
getIntent().putExtra(ARTISTS_KEY,artistList);
} else {
getIntent().putExtra(ARTISTS_KEY,"No artists found");
}
if (!albumList.isEmpty()){
getIntent().putExtra(ALBUMS_KEY,albumList);
} else {
getIntent().putExtra(ALBUMS_KEY,"No albums found");
}
}
}
The code below, SongsTab.java, gets songList extra and displays the items in a ListView
package com.newton.hooked.ui.main;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.newton.hooked.MediaGalleryActivity;
import com.newton.hooked.PlayerActivity;
import com.newton.hooked.R;
import java.util.ArrayList;
import java.util.Objects;
public class SongsTab extends Fragment {
public static final String SONG_POSITION = "POSITION";
private ListView songList;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.songs_tab, container, false);
songList = view.findViewById(R.id.song_list);
TextView message = view.findViewById(R.id.song_message);
Intent intent = Objects.requireNonNull(getActivity()).getIntent();
final ArrayList<String> songs = intent.getStringArrayListExtra(MediaGalleryActivity.SONGS_KEY);
if (!songs.isEmpty()){
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(Objects.requireNonNull(getContext()),R.layout.display_layout_2,R.id.txt_name,songs);
songList.setAdapter(arrayAdapter);
songList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(getActivity(), PlayerActivity.class)
.putExtra("SONGLIST",songs)
.putExtra(SONG_POSITION,position)
.putExtra("SONG_ID",id));
}
});
} else {
songList.setVisibility(View.INVISIBLE);
message.setVisibility(View.VISIBLE);
}
return view;
}
}
The code below, PlayerActivity.java, is supposed to play a selected song:
package com.newton.hooked;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentUris;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.newton.hooked.ui.main.SongsTab;
import java.io.File;
import java.util.ArrayList;
public class PlayerActivity extends AppCompatActivity {
Button btn_next, btn_previous, btn_pause;
TextView songTextLabel;
SeekBar songSeekBar;
String sName;
MediaPlayer myMediaPlayer = new MediaPlayer();
int position = 0;
ArrayList<String> mySongs = new ArrayList<>();
Thread updateSeekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
btn_next = findViewById(R.id.next);
btn_pause = findViewById(R.id.pause);
btn_previous = findViewById(R.id.previous);
songTextLabel = findViewById(R.id.song_label);
songSeekBar = findViewById(R.id.seek_bar);
getSupportActionBar().setTitle("Now Playing...");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
updateSeekBar = new Thread(){
#Override
public void run() {
int totalDuration = myMediaPlayer.getDuration();
int currentPosition = 0;
while (currentPosition<totalDuration){
try {
sleep(500);
currentPosition= myMediaPlayer.getCurrentPosition();
songSeekBar.setProgress(currentPosition);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
};
if(myMediaPlayer!=null){
myMediaPlayer.stop();
myMediaPlayer.release();
}
Intent i = getIntent();
mySongs = i.getStringArrayListExtra("SONGLIST");
position = i.getIntExtra(SongsTab.SONG_POSITION, 0);
String songName= i.getStringExtra("songName");
long songID = i.getIntExtra("SONG_ID",0);
songTextLabel.setText(songName);
songTextLabel.setSelected(true);
Uri u = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,songID);
myMediaPlayer = MediaPlayer.create(PlayerActivity.this,u);
myMediaPlayer.start();
songSeekBar.setMax(myMediaPlayer.getDuration());
updateSeekBar.start();
songSeekBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.black), PorterDuff.Mode.MULTIPLY);
songSeekBar.getThumb().setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_IN);
songSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
myMediaPlayer.seekTo(seekBar.getProgress());
}
});
btn_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
songSeekBar.setMax(myMediaPlayer.getDuration());
if(myMediaPlayer.isPlaying()){
btn_pause.setBackgroundResource(R.drawable.icon_play);
myMediaPlayer.pause();
} else {
btn_pause.setBackgroundResource(R.drawable.icon_pause);
myMediaPlayer.start();
}
}
});
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.stop();
myMediaPlayer.release();
position = ((position +1)%mySongs.size());
Uri u = Uri.parse(mySongs.get(position).toString());
myMediaPlayer = MediaPlayer.create(getApplicationContext(), u);
sName = mySongs.get(position).toString();
songTextLabel.setText(sName);
myMediaPlayer.start();
}
});
btn_previous.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMediaPlayer.stop();
myMediaPlayer.release();
position = ((position -1)%mySongs.size()-1);
Uri u = Uri.parse(mySongs.get(position).toString());
myMediaPlayer = MediaPlayer.create(getApplicationContext(), u);
sName = mySongs.get(position).toString();
songTextLabel.setText(sName);
myMediaPlayer.start();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home){
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
When I run the app, I encounter the error below:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.newton.hooked, PID: 2396
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.newton.hooked/com.newton.hooked.PlayerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2505)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2577)
at android.app.ActivityThread.access$1000(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:160)
at android.app.ActivityThread.main(ActivityThread.java:5541)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.newton.hooked.PlayerActivity.onCreate(PlayerActivity.java:90)
at android.app.Activity.performCreate(Activity.java:6093)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2458)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2577)
at android.app.ActivityThread.access$1000(ActivityThread.java:164)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:160)
at android.app.ActivityThread.main(ActivityThread.java:5541)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:964)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:759)
Assistance would be much appreciated.
I am loosely following a guide but I am using an onClickListener to start the search process. I am in the process of implementing a Loader here:
getSupportLoaderManager().restartLoader(0,queryBundle,this);
but when I put in ‘this’ it brings up the following message:
Wrong 3rd argument type. Found: 'android.view.View.OnClickListener', required: 'android.support.v4.app.LoaderManager.
LoaderCallbacks'
I am loathed to change from an onClickListener to a onClick method as the guide suggests, is there a way to implement the Loader in the onClickListener?
The code is below:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GoogleBookActivity extends AppCompatActivity implements
LoaderManager.LoaderCallbacks<String>{
private static final String TAG = GoogleBookActivity.class.getSimpleName();
private EditText mEditText;
private BookAdapter mAdapter;
private Button bookSearch;
private TextView mTitle, mAuthor;
//URL link to the API
private static final String GOOGLE_BOOKS_REQUEST_URL = "https://www.googleapis.com/books/v1/volumes?q=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_google_book);
mTitle = (TextView) findViewById(R.id.book_title);
mAuthor = (TextView) findViewById(R.id.book_author);
bookSearch = (Button) findViewById(R.id.searchbutton);
mEditText = (EditText) findViewById(R.id.search_text);
bookSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Initialise String queryText
String queryText = mEditText.getText().toString();
//For Hiding the keyboard when the search button is clicked
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromInputMethod(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
//For Checking the network status and empty search field case
ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo !=null && networkInfo.isConnected() && queryText.length()!=0){
//new FetchBook(mTitle, mAuthor).execute(queryText);
}
Log.i(TAG, "Searched " + queryText);
if(queryText.length() != 0){
new FetchBook(mTitle, mAuthor).execute(queryText);
mAuthor.setText("");
mTitle.setText(R.string.loading);
//We replace the call to execute the fetchbook task with a call to restartLoader(), passing in
// the querystring you get from the EditText in the Bundle.
Bundle queryBundle = new Bundle();
queryBundle.putString("queryText", queryText);
getSupportLoaderManager().restartLoader(0,queryBundle,this);
}else {
if(queryText.length() == 0){
mAuthor.setText("");
mTitle.setText("Please enter a search term.");
}else{
mAuthor.setText("");
mTitle.setText("Please check your network connection and try again.");
}
}
}
});
}
#Override
public Loader<String> onCreateLoader(int i, Bundle bundle) {
return null;
}
#Override
public void onLoadFinished(Loader<String> loader, String s) {
}
#Override
public void onLoaderReset(Loader<String> loader) {
}
}
this refers to the encapsulating OnClickListener:
bookSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// You are now inside an anonymous class extending from
// OnClickListener. 'this' now refers to this very instance
// of the OnClickListener
}
});
In order to refer to the encapsulating GoogleBookActivity, just type that class name in front:
getSupportLoaderManager().restartLoader(0, queryBundle, GoogleBookActivity.this);
Im trying to make an app with buttons to call different phone numbers. I have this:
package com.BigTooth.Apps.Recromax;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.Intent;
import android.content.*;
import android.net.Uri;
import android.view.View.OnClickListener;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private void phoneCall1()
{
String phoneCallUri = "tel:4078421430";
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
// add button listener
button.setOnClickListener(new OnClickListener() {
private void phoneCall()
{
String phoneCallUri = "tel:8889807091";
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);}
}
}
In my MainActivity.java file. Its telling me that isn't correct. Please help!!!
button.setOnClickListener is in the wrong place. Also, the onClickListener is a bit wring. Should be:
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.content.Intent;
import android.content.*;
import android.net.Uri;
import android.view.View.OnClickListener;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.youButtonId);
Button button1 = (Button) findViewById(R.id.youButtonId1);
// add button listener
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
phoneCall();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
phoneCall1();
}
});
}
private void phoneCall()
{
String phoneCallUri = "tel:8889807091";
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
private void phoneCall1()
{
String phoneCallUri = "tel:4078421430";
Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
}