A way to save Arraylist on device? - java

So I have this little application where you can call from.
In this application, You will be able to log in with your phone-number and get a number from our server (This is not implemented YET)
Depending on "Who you are", our server will give you a number dynamically.
This is not really relevant, but it still has some things to do with my question.
Since our server gives the number, I can't make a "Recent List" with the info I get from Android CallLogs. (It may get numbers A.E "Mom" into your professional contact list, etc etc)
So what I'm doing now, is after each call, insert the info (Name,Number,Date and Duration) Into an Array List.
recentCalls.add(new Recent(aName, aDate, aNumber, "0"));
(0 stands for Seconds, of Duration. Still not completed.)
It would "Save" in the app momentarily, and when the application is fully killed (Or Crashes), everything would be emptied out.
I have considered Saving the Array list in SharedPreferences.
But since we're going to limit the recents to 100, this will be too big.
I have read this: Android Storage Options
Either way, I AM still getting all the call logs from the phone itself, for testing purposes.
My questions are:
How could I save an ArrayList Safely and Efficiently
If I'm not going to work with an ArrayList, How could I "Format" the ACTUAL phone's call_logs to only show numbers dialed from my app. (In order to call "Through" our server, we use "ServerPhoneNumber" + "," + "Inserted PhoneNumber" - Example: 123456789,987654321)
Could I say Check if 1st 10 characters equal to "123456789"? Which is not possible, since it changes the number depending on the person.
Here's my Java Code:
package com.example.dragonphone;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.LightingColorFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
public class Tabs extends Activity implements OnClickListener, OnLongClickListener{
TabHost th;
TabSpec specs;
TextView numberfield;
ListView recents;
public String string,number;
private List<Recent> recentCalls = new ArrayList<Recent>();
public int counter;
Button n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,nstar,nhash,sms,contact,call,clear,clearhistory,getinfo;
//ImageView call, clear;
public Vibrator vib;
//public String phoneNumber;
String date = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
th = (TabHost)findViewById(R.id.tabhost);
numberfield = (TextView) findViewById(R.id.etNumberField);
n1 = (Button) findViewById (R.id.bNumber1);
n2 = (Button) findViewById (R.id.bNumber2);
n3 = (Button) findViewById (R.id.bNumber3);
n4 = (Button) findViewById (R.id.bNumber4);
n5 = (Button) findViewById (R.id.bNumber5);
n6 = (Button) findViewById (R.id.bNumber6);
n7 = (Button) findViewById (R.id.bNumber7);
n8 = (Button) findViewById (R.id.bNumber8);
n9 = (Button) findViewById (R.id.bNumber9);
nstar = (Button) findViewById (R.id.bNumberStar);
n0 = (Button) findViewById (R.id.bNumber0);
nhash = (Button) findViewById (R.id.bNumberHash);
call = (Button) findViewById (R.id.bCall);
sms = (Button) findViewById (R.id.bSMS);
clear = (Button) findViewById (R.id.bClear);
contact = (Button) findViewById (R.id.bContact);
recents = (ListView) findViewById (R.id.recentList);
clearhistory = (Button) findViewById (R.id.bClearHistory);
getinfo = (Button) findViewById (R.id.bGetCallDetails);
populateRecentList();
populateListView();
registerClickCallback();
th.setBackgroundColor(Color.rgb(202, 233, 252));
//n1.getBackground().setColorFilter(new LightingColorFilter(0x000033, 0x000099));
sms.getBackground().setColorFilter(new LightingColorFilter(0xFFFF66, 0xFFFF00));
vib = (Vibrator) getSystemService(VIBRATOR_SERVICE);
n1.setOnClickListener(this);
n2.setOnClickListener(this);
n3.setOnClickListener(this);
n4.setOnClickListener(this);
n5.setOnClickListener(this);
n6.setOnClickListener(this);
n7.setOnClickListener(this);
n8.setOnClickListener(this);
n9.setOnClickListener(this);
nstar.setOnClickListener(this);
n0.setOnClickListener(this);
n0.setOnLongClickListener(this);
nhash.setOnClickListener(this);
call.setOnClickListener(this);
clear.setOnClickListener(this);
clear.setOnLongClickListener(this);
sms.setOnClickListener(this);
contact.setOnClickListener(this);
clearhistory.setOnClickListener(this);
getinfo.setOnClickListener(this);
th.setup();
specs = th.newTabSpec("tag1");
specs.setContent(R.id.Recents);
specs.setIndicator("Recent Calls");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.Keypad);
specs.setIndicator("Keypad");
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.Sms);
specs.setIndicator("SMS");
th.addTab(specs);
specs = th.newTabSpec("tag4");
specs.setContent(R.id.Ratings);
specs.setIndicator("Rates");
th.addTab(specs);
specs = th.newTabSpec("tag5");
specs.setContent(R.id.Account);
specs.setIndicator("Account");
th.addTab(specs);
}
private void populateRecentList() {
//TODO Auto-generated method stub
recentCalls.add(new Recent("Zach", "01-12-2013", "064555246", "600"));
recentCalls.add(new Recent("Adam", "11-12-2013", "00355563315","510"));
recentCalls.add(new Recent("John", "03-12-2013", "00955587", "100"));
recentCalls.add(new Recent("Jorge", "15-10-2013" , "445559585", "60"));
}
private void populateListView() {
// TODO Auto-generated method stub
ArrayAdapter<Recent> adapter = new MyRecentAdapter();
ListView list = (ListView) findViewById(R.id.recentList);
list.setAdapter(adapter);
}
private class MyRecentAdapter extends ArrayAdapter<Recent>{
public MyRecentAdapter(){
super(Tabs.this, R.layout.recents_view, recentCalls);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
//Make sure we have a view to work with
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.recents_view, parent,false);
}
Recent currentCall = recentCalls.get(position);
TextView nameText = (TextView) itemView.findViewById(R.id.tvRecentName);
nameText.setText(currentCall.getName());
TextView numberText = (TextView) itemView.findViewById(R.id.tvRecentNumber);
numberText.setText(currentCall.getPn());
TextView dateText = (TextView) itemView.findViewById(R.id.tvRecentDate);
dateText.setText("" + currentCall.getDate());
TextView durationText = (TextView) itemView.findViewById(R.id.tvRecentDuration);
durationText.setText("" + currentCall.getDuration());
return itemView;
// return super.getView(position, convertView, parent);
}
}
private void registerClickCallback() {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.recentList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
// TODO Auto-generated method stub
Recent clickedCall = recentCalls.get(position);
String name = clickedCall.getName();
numberfield.setText(clickedCall.getPn());
counter = numberfield.getText().toString().length();
String message = "Calling " + name;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, message, duration);
toast.show();
call();
}
});
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bNumber1:
numberfield.setText(numberfield.getText() + "1");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber2:
numberfield.setText(numberfield.getText() + "2");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber3:
numberfield.setText(numberfield.getText() + "3");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber4:
numberfield.setText(numberfield.getText() + "4");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber5:
numberfield.setText(numberfield.getText() + "5");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber6:
numberfield.setText(numberfield.getText() + "6");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber7:
numberfield.setText(numberfield.getText() + "7");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber8:
numberfield.setText(numberfield.getText() + "8");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber9:
numberfield.setText(numberfield.getText() + "9");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumberStar:
numberfield.setText(numberfield.getText() + "*");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumber0:
numberfield.setText(numberfield.getText() + "0");
addCheck();
vib.vibrate(25);
break;
case R.id.bNumberHash:
numberfield.setText(numberfield.getText() + "#");
addCheck();
vib.vibrate(25);
break;
case R.id.bClear:
String number = numberfield.getText().toString();
if(number.length() > 0){
String newNumber = number.substring(0, number.length()-1);
numberfield.setText(newNumber);
deleteCheck();
vib.vibrate(25);
}else{
Context context = getApplicationContext();
CharSequence text = "The numbers are already cleared.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
case R.id.bCall:
call();
break;
case R.id.bContact:
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
break;
case R.id.bClearHistory:
recentCalls.clear();
CharSequence text = "Your recent list has been cleared.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, text, duration);
toast.show();
th.setCurrentTabByTag("tag1");
break;
case R.id.bSMS:
th.setCurrentTabByTag("tag3");
CharSequence text2 = "This function is still under construction..";
int duration2 = Toast.LENGTH_LONG;
Toast toast2 = Toast.makeText(this, text2, duration2);
toast2.show();
break;
case R.id.bGetCallDetails:
getCallDetails();
break;
}
}
private void deleteCheck() {
// TODO Auto-generated method stub
counter --;
if(counter < 14){
numberfield.setTextSize(25); //Set text size when amount goes lower.
}
if(counter >= 14 && counter < 16){
numberfield.setTextSize(20); //Set text size when amount goes lower.
}
if(counter >= 16 && counter < 18){
numberfield.setTextSize(18);
}
if(counter >= 18 && counter < 20){
numberfield.setTextSize(16);
}
}
private void addCheck() {
// TODO Auto-generated method stub
counter++;
if(counter >= 14){
numberfield.setTextSize(20); //Set text size when amount goes higher.
//numberfield.setMaxHeight(10);
}
if(counter >= 16){
numberfield.setTextSize(18); //Set text size when amount goes higher.
}
if(counter >= 18){
numberfield.setTextSize(16); //Set text size when amount goes higher.
}
if(counter >= 20){
numberfield.setTextSize(14); //Set text size when amount goes higher.
}
if(counter < 14){
numberfield.setTextSize(25); //Set text size when amount goes lower.
}
if(counter >= 14 && counter < 16){
numberfield.setTextSize(20); //Set text size when amount goes lower.
}
if(counter >= 16 && counter < 18){
numberfield.setTextSize(18);
}
if(counter >= 18 && counter < 20){
numberfield.setTextSize(16);
}
}
private void getCallDetails() {
StringBuilder sb = new StringBuilder();
Uri contacts = CallLog.Calls.CONTENT_URI;
Cursor managedCursor = this.getContentResolver().query(contacts, null, null, null,CallLog.Calls.DATE + " DESC LIMIT 100");
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details :");
while (managedCursor.moveToNext()) {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
String callDayTime = new Date(Long.valueOf(callDate)).toString();
// long timestamp = convertDateToTimestamp(callDayTime);
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- " + dir + " \nCall Date:--- " + callDayTime + " \nCall duration in sec :--- " + callDuration);
sb.append("\n----------------------------------");
}
managedCursor.close();
System.out.println(sb);
}
private void call() {
// TODO Auto-generated method stub
if(number.length() > 0){
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String dsPhoneNumber = "+34965063314,"; // Dynamic number
//965063064
string = numberfield.getText().toString().trim();
number = "tel:" + dsPhoneNumber + string;
callIntent.setData(Uri.parse(number));
startActivity(callIntent);
//recentCalls.add(new Recent(aName, aDate, aNumber, "0"));
} catch (ActivityNotFoundException activityException) {
Log.e("helloandroid dialing example", "Call failed");
}
}else {
Context context = getApplicationContext();
CharSequence text = "Please insert a phone number or choose a contact.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
#Override
public boolean onLongClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.bClear:
if(counter != 0){
counter = 0;
numberfield.setTextSize(25);
numberfield.setText("");
vib.vibrate(100);}
else{
Context context = getApplicationContext();
CharSequence text = "The numbers are already cleared.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
break;
case R.id.bNumber0:
numberfield.setText(numberfield.getText() + "+");
addCheck();
vib.vibrate(25);
break;
}
return true;
}
public void onActivityResult(int reqCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
Cursor cursor=this.getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(cursor.getString( cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// You now have the number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
numberfield.setText(phoneNumber);
counter = numberfield.getText().toString().length();
/*if(counter == 0){
Context context = getApplicationContext();
//CharSequence text = counter;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, counter, duration);
toast.show();
}*/
}
phones.close();
}
}
}
}
}
Thanks in Advance!
EDIT
private void registerClickCallback() {
// TODO Auto-generated method stub
ListView list = (ListView) findViewById(R.id.recentList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
// TODO Auto-generated method stub
Recent clickedCall = recentCalls.get(position);
// String name = clickedCall.getName();
//numberfield.setText(clickedCall.getPn());
counter = numberfield.getText().toString().length();
// String message = getResources().getString(R.string.toastCalling) + " " + name + " " + getResources().getString(R.string.toastCalling2);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
//Toast toast = Toast.makeText(context, message, duration);
//toast.show();
call();
}
});
}
This is my current call method. (Commented out stuff since it's not like the old code anymore.)
Basically whenever I click call,
case R.id.bCall:
call();
The Call function:
private void call() {
// TODO Auto-generated method stub
if(numberfield.length() > 0){
try {
Intent callIntent = new Intent(Intent.ACTION_CALL);
String dsPhoneNumber = "+34965063314,";
// Dynamic number
//965063064
String string = numberfield.getText().toString().trim();
number = "tel:" + dsPhoneNumber + string;
callIntent.setData(Uri.parse(number));
startActivity(callIntent);
//recentCalls.add(new Recent(aName, aDate, aNumber, "0"));
} catch (ActivityNotFoundException activityException) {
Log.e("helloandroid dialing example", "Call failed");
}
}else {
Context context = getApplicationContext();
CharSequence text = getResources().getText(R.string.keypadViewToastEmptyNumber);
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
It needs to Insert it in the "List" and show it on the Recents tab.
I've spent a couple of hours trying to solve this, No progress. Thanks in advance!
Edit #2
public View getView(int position, View convertView, ViewGroup parent){
//Make sure we have a view to work with
View itemView = convertView;
if(itemView == null)
{
itemView = getLayoutInflater().inflate(R.layout.recents_view, parent,false);
}
Recent currentCall = recentCalls.get(position);
TextView nameText = (TextView) itemView.findViewById(R.id.tvRecentName);
nameText.setText(currentCall.getName());
TextView numberText = (TextView) itemView.findViewById(R.id.tvRecentNumber);
numberText.setText(currentCall.getPn());
TextView dateText = (TextView) itemView.findViewById(R.id.tvRecentDate);
dateText.setText("" + currentCall.getDate());
TextView durationText = (TextView) itemView.findViewById(R.id.tvRecentDuration);
durationText.setText("" + currentCall.getDuration());
return itemView;
// return super.getView(position, convertView, parent);
}
}
So this is the view of the recents tab. The .getDate/.getDuration etc are changed, What should the "new one" be? So basically read

What I would do is the following:
Get a java.io.File to a local (/data/data/f.q.c.n/files/recents) file
Open a (buffered) FileOutputStream to it
Write the elements of the ArrayList<Recent> to the file
Write the name as byte-array (String.getBytes)
Write the date as a long (since epoch)
Write the number as a string (as there can be different formats)
Write the duration as an int
Note that long and int are fixed-size and therefore can be read easily
You can prefix the byte-array with an int, indicating it's size
Then, of course, you do the same thing in reverse on startup, to rebuild that ArrayList.
Someone called this approach controlled binary serialization. Of course you can have it easier, but it's not really hard to do and you get rid of all reflection (which can have awful performance on early Android devices). This is the fastest (smoothest) approach I can think of.
I didn't choose standard Serialization because it sucks (Tons of reflection and metadata).
Note that SharedPreferences have been successfully (ab-) used to store much larger data than you have.
Example:
IO.java:
import java.io.IOException;
public interface IO {
void write(DataOutputStream out) throws IOException;
void read(DataInputStream in) throws IOException;
}
Recent.java:
import java.io.IOException;
import java.util.Date;
public class Recent implements IO {
private String name, number;
private Date date;
private int duration; // in milliseconds
public Recent(String name, String number, Date date, int duration) {
this.name = name;
this.number = number;
this.date = date;
this.duration = duration;
}
public Recent() {
this(null, null, null, 0);
}
#Override
public void write(DataOutputStream out) throws IOException {
byte[] nameData = name.getBytes("UTF-8");
out.writeInt(nameData.length);
out.write(nameData);
byte[] numberData = number.getBytes("UTF-8");
out.writeInt(numberData.length);
out.write(numberData);
out.writeLong(date.getTime());
out.writeInt(duration);
}
#Override
public void read(DataInputStream in) throws IOException {
int nameDataLength = in.readInt();
if (nameDataLength > 100000) throw new IllegalStateException("Name shouldn't be this long: " + nameDataLength);
byte[] nameData = new byte[nameDataLength];
in.readFully(nameData);
name = new String(nameData, "UTF-8");
int numberDataLength = in.readInt();
if (numberDataLength > 100000) throw new IllegalStateException("Number shouldn't be this long: " + nameDataLength);
byte[] numberData = new byte[numberDataLength];
in.readFully(numberData);
number = new String(numberData, "UTF-8");
date = new Date(in.readLong());
duration = in.readInt();
}
}
RecentsList.java:
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class RecentsList implements IO {
private List<Recent> recents;
public RecentsList() {
recents = new ArrayList<Recent>();
}
public void addRecent(Recent recent) {
recents.add(recent);
}
#Override
public void write(DataOutputStream out) throws IOException {
out.writeInt(recents.size());
for (Recent r : recents) {
r.write(out);
}
}
#Override
public void read(DataInputStream in) throws IOException {
int size = in.readInt();
recents = new ArrayList<Recent>(size);
for (int i = 0; i < size; i++) {
Recent r = new Recent();
r.read(in);
recents.add(r);
}
}
public static void main(String[] args) throws IOException {
RecentsList test = new RecentsList();
// build test data
for (int i = 0; i < 100; i++) {
String iString = Integer.toString(i);
Recent r = new Recent(iString, iString, new Date(), i);
test.addRecent(r);
}
// write
File out = new File("/home/till/recents.bin");
DataOutputStream dataOut = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(out)));
test.write(dataOut);
dataOut.close();
// read
RecentsList read = new RecentsList();
DataInputStream dataIn = new DataInputStream(new BufferedInputStream(new FileInputStream(out)));
read.read(dataIn);
dataIn.close();
System.out.println("read now contains same data as test if everything went ok");
}
}
Note:
You will wan't to simplify writing and reading a byte-array. I do that myself but didn't include it for briefness (it's long enough already)
The imports for the Data[Input|Output]Stream are missing
You may wan't to change the size for the exception
You can shrink the ints for small numbers
If you have any problems/questions, don't hesitate to comment!

Related

Creating a putExtra to another class won't work

So I am trying to pass data from my HomePage.class(my main activity) to my ContactHelper class but it just seems to crash.
This is the code that crashes the app:
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
Which is inside my getContacts function:
#SuppressLint("Range")
private void getContacts(View view) {
// this method is use to read contact from users device.
// on below line we are creating a string variables for
// our contact id and display name.
String contactId = "";
String displayName = "";
String phone = "";
String contactEmail = "";
String Amount = "0";
String CurDate = "11111111";
String DueDate = "99999999";
String TimeCur = "0";
String TimeDue = "0";
// on below line we are calling our content resolver for getting contacts
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// on blow line we are checking the count for our cursor.
if (cursor.getCount() > 0) {
// if the count is greater than 0 then we are running a loop to move our cursor to next.
while (cursor.moveToNext()) {
// on below line we are getting the phone number.
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
// we are checking if the has phone number is > 0
// on below line we are getting our contact id and user name for that contact
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// on below line we are calling a content resolver and making a query
Cursor phoneCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{contactId},
null);
// on below line we are moving our cursor to next position.
if (phoneCursor.moveToNext()) {
// on below line we are getting the phone number for our users and then adding the name along with phone number in array list.
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactsModalArrayList.add(new ContactsModal(displayName, phoneNumber));
}
// on below line we are closing our phone cursor.
phoneCursor.close();
}
}
Context context = view.getContext();
Intent i = new Intent(context, ContactHelper.class);
i.putExtra("name", displayName);
i.putExtra("phone", phone);
i.putExtra("email", contactEmail);
i.putExtra("amount", Amount);
i.putExtra("curDate", CurDate);
i.putExtra("dueDate", DueDate);
i.putExtra("curTime", TimeCur);
i.putExtra("timeDue", TimeDue);
//on below line we are starting a new activity,
context.startActivity(i);
}
// on below line we are closing our cursor.
cursor.close();
// on below line we are hiding our progress bar and notifying our adapter class.
loadingPB.setVisibility(View.GONE);
contactRVAdapter.notifyDataSetChanged();
}
I am trying to pass the intent to the class below to a function named getContactInfo:
package com.example.myan;
import android.app.AlertDialog;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract.RawContacts;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class ContactHelper extends AppCompatActivity {
static Context context;
static String number;
static String newName;
static String newNumber;
public static Cursor getContactCursor(ContentResolver contactHelper,
String startsWith) {
String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER };
Cursor cur = null;
try {
if (startsWith != null && !startsWith.equals("")) {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " like \"" + startsWith + "%\"", null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
} else {
cur = contactHelper.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
projection, null, null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
}
cur.moveToFirst();
} catch (Exception e) {
e.printStackTrace();
}
return cur;
}
public void getContactInfo(View view) {
Intent intent = getIntent();
String getName = intent.getStringExtra("name");
String getPhone = intent.getStringExtra("phone");
String getEmail = intent.getStringExtra("email");
String getAmount = intent.getStringExtra("amount");
String getCurDate = intent.getStringExtra("curDate");
String getDueDate = intent.getStringExtra("dueDate");
String getCurTime = intent.getStringExtra("curTime");
String getTimeDue = intent.getStringExtra("timeDue");
Integer getFirstDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(3)));
Integer getFirstDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getCurDate).charAt(2)));
String getFirstDateNumber = String.valueOf(getFirstDate3rdValue) + String.valueOf(getFirstDate4thValue);
Integer getSecondDate4thValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(3)));
Integer getSecondDate3rdValue = Integer.valueOf(String.valueOf(intent.getStringExtra(getDueDate).charAt(2)));
String getSecondDateNumber = String.valueOf(getSecondDate3rdValue) + String.valueOf(getSecondDate4thValue);
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) > 0) {
view.findViewById(R.id.txtfront).setVisibility(View.VISIBLE);
}
if (Integer.valueOf(String.valueOf(intent.getStringExtra(getAmount))) == 0) {
view.findViewById(R.id.txtfront).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) != Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
}
if (Integer.valueOf(getFirstDateNumber) == Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
view.findViewById(R.id.txtDueToday).setVisibility(View.VISIBLE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) + " owes you $" + intent.getStringExtra(getAmount) + ".00 today at " + intent.getStringExtra(getTimeDue) + " O'Clock.");
alertDialogBuilder.setIcon(R.drawable.ic_launcher_background);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) > Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.VISIBLE);
view.findViewById(R.id.txtDueToday).setVisibility(View.GONE);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(intent.getStringExtra(getName) + " is late and has owed you on " + intent.getStringExtra(getDueDate) + " and owes you $" + intent.getStringExtra(getAmount) + ".00");
alertDialogBuilder.setIcon(R.drawable.myanlogo);
alertDialogBuilder.setTitle("MYAN");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
if (Integer.valueOf(getFirstDateNumber) < Integer.valueOf(getSecondDateNumber)) {
view.findViewById(R.id.txtLate).setVisibility(View.GONE);
}
}
public static long getContactID(ContentResolver contactHelper,
String phone) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phone));
String[] projection = { PhoneLookup._ID };
Cursor cursor = null;
try {
cursor = contactHelper.query(contactUri, projection, null, null,
null);
if (cursor.moveToFirst()) {
int personID = cursor.getColumnIndex(PhoneLookup._ID);
return cursor.getLong(personID);
}
return -1;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
}
return -1;
}
public static void deleteContact(ContentResolver contactHelper,
String number) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] { String.valueOf(getContactID(
contactHelper, number)) };
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(RawContacts.CONTACT_ID + "=?", args).build());
try {
contactHelper.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
Why would it be crashing?
My ultimate goal here is to have objects in my ContactsRVAdapter to become visible and not visible, and also text change, like current date and time.
[This is the FloatingActionButton which I am trying to manipulate][1]
Which is in a RecyclerView
But I cant seem to reach the items in my FloatingActionButton(ContactsRVAdapter) in any way.
Here is my ContactsRVAdapter class:
package com.example.myan;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.net.URISyntaxException;
import java.util.ArrayList;
class ContactRVAdapter extends RecyclerView.Adapter<ContactRVAdapter.ViewHolder> {
public static final String CHANNEL_1="CHANNEL1";
// creating variables for context and array list.
private Context context;
private ArrayList<ContactsModal> contactsModalArrayList;
private ContentResolver contactHelper;
private String number;
private TextView contactLate;
private View view;
private Intent intent;
// creating a constructor
public ContactRVAdapter(Context context, ArrayList<ContactsModal> contactsModalArrayList) {
this.context = context;
this.contactsModalArrayList = contactsModalArrayList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
try {
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.contacts_rv_item, parent, false));
} catch (URISyntaxException e) {
e.printStackTrace();
}
return null;
}
// below method is use for filtering data in our array list
public void filterList(ArrayList<ContactsModal> filterlist) {
// on below line we are passing filtered
// array list in our original array list
contactsModalArrayList = filterlist;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
// getting data from array list in our modal.
ContactsModal modal = contactsModalArrayList.get(position);
// on below line we are setting data to our text view.
holder.contactTV.setText(modal.getUserName());
ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
// generate random color
int color = generator.getRandomColor();
// below text drawable is a circular.
TextDrawable drawable2 = TextDrawable.builder().beginConfig()
.width(100) // width in px
.height(100) // height in px
.endConfig()
// as we are building a circular drawable
// we are calling a build round method.
// in that method we are passing our text and color.
.buildRound(modal.getUserName().substring(0, 1), color);
// setting image to our image view on below line.
holder.contactIV.setImageDrawable(drawable2);
// on below line we are adding on click listener to our item of recycler view.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// on below line we are opening a new activity and passing data to it.
Intent i = new Intent(context, ContactDetailActivity.class);
i.putExtra("name", modal.getUserName());
i.putExtra("contact", modal.getContactNumber());
//on below line we are starting a new activity,
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return contactsModalArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView contactLate;
public ImageView txtFront;
// on below line creating a variable
// for our image view and text view.
private ImageView contactIV;
private TextView contactTV;
private ImageView btnDeleteContact;
private ImageView textDueToday;
private Intent intent;
private String getName;
private String getPhone;
private String getEmail;
private String getAmount;
private String getCurDate;
private String getDateDue;
private String getCurTime;
private String getDueTime;
public ViewHolder(#NonNull View itemView) throws URISyntaxException {
super(itemView);
// initializing our image view and text view.
contactIV = itemView.findViewById(R.id.idIVContact);
contactTV = itemView.findViewById(R.id.idTVContactName);
//contactLate = itemView.findViewById(R.id.txtLate);
//txtFront = itemView.findViewById(R.id.txtfront);
//textDueToday = itemView.findViewById(R.id.txtDueToday);
}
}
}
So all I am trying to do is make it to where I can manipulate the objects inside ContactsRVAdapter class which is a Floating action button.
And my Logcat
FATAL EXCEPTION: main
Process: com.example.myan, PID: 1719
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myan/com.example.myan.HomePage}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3645)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3782)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:101)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2307)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.View.getContext()' on a null object reference
at com.example.myan.HomePage.getContacts(HomePage.java:286)
at com.example.myan.HomePage.access$200(HomePage.java:39)
at com.example.myan.HomePage$4.onPermissionsChecked(HomePage.java:159)
at com.karumi.dexter.DexterInstance$1.run(Unknown Source:43)
at com.karumi.dexter.MainThread.execute(Unknown Source:6)
at com.karumi.dexter.DexterInstance.checkMultiplePermissions(Unknown Source:71)
at com.karumi.dexter.DexterInstance.checkPermissions(Unknown Source:0)
at com.karumi.dexter.Dexter.check(Unknown Source:10)
at com.example.myan.HomePage.requestPermissions(HomePage.java:187)
at com.example.myan.HomePage.onCreate(HomePage.java:69)
at android.app.Activity.performCreate(Activity.java:8305)
at android.app.Activity.performCreate(Activity.java:8284)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1417)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3626)
try this code...
Intent i = new Intent(this, ContactHelper.class);
The crash is in your view. You are passing view of an activity, which doesn't exist or has been finished.
Context context = view.getContext();
In this function, pass context of existing activity.
private void getContacts(View view) {
...
}
Check the datatypes of the data that you are parsing in Another activities. It should be parcelable or serializable.

Accessing shared preferences in a non-activity class from fragment class

I have a fragment:
public class TodayVerse extends Fragment
{
TextView textView;
DailyQuranMethods dailyQuranMethods;
public TodayVerse() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_today_verse, container, false);
textView = (TextView) view.findViewById(R.id.verse);
// setChapterVerse();
textView.setText(dailyQuranMethods.getVerseToday(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()) + "\nChapter:" + dailyQuranMethods.getChapterTodayName(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()));
return view;
}
}
This fragment calls a non-activity class :
dailyQuranMethods which uses sharedPrefrences. For the purpose, I had to pass a Context as parameter. I passed:
getActivity().getApplicationContext()
The methods in dailyQuranMethods are like:
public String getVerseToday(String today,Context context){
...
}
On running the app, I have following logcat:
06-19 06:07:56.587 9887-9887/? E/AndroidRuntime﹕ FATAL EXCEPTION:
main
java.lang.NullPointerException
at com.example.shiza.dailyquranverses.TodayVerse.onCreateView(TodayVerse.java:35)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
at android.support.v4.app.FragmentTabHost.onAttachedToWindow(FragmentTabHost.java:283)
at android.view.View.dispatchAttachedToWindow(View.java:9788)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2198)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2206)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:971)
at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2467)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
The error is in the following line:
textView.setText(dailyQuranMethods.getVerseToday(dailyQuranMethods.DateToday(),getActivity().getApplicationContext())
+ "\nChapter:" + dailyQuranMethods.getChapterTodayName(dailyQuranMethods.DateToday(),getActivity().getApplicationContext()));
Looks like, I am unable to get Context in my non-activity class. I tried a lot, but nothing helped. Please help me to solve this.
Edit 1 : The non-activity class is:
package com.example.shiza.dailyquranverses;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.MatrixCursor;
import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.widget.SimpleCursorAdapter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
import com.example.shiza.dailyquranverses.TodayChapter;
import android.preference.Preference;
/**
* Created by Shiza on 19-06-2015.
*/
public class DailyQuranMethods {
// generate a random number.
SharedPreferences sharedPreferencesChapter;
SharedPreferences sharedPreferencesVerse;
private static String TODAY_CHAPTER = "TODAY_CHAPTER";
private static String TODAY_VERSE = "TODAY_VERSE";
Context context;
public int GetRandom(int min, int max) {
Random ran = new Random();
return ran.nextInt((max - min) + 1) + min;
}
public void setChapterVerseOfToday(Context context)
{
sharedPreferencesChapter = context.getSharedPreferences(TODAY_CHAPTER, Context.MODE_PRIVATE);
sharedPreferencesVerse = context.getApplicationContext().getSharedPreferences(TODAY_VERSE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor_chapter = sharedPreferencesChapter.edit();
SharedPreferences.Editor editor_verse = sharedPreferencesVerse.edit();
int chapter_no = GetRandom(1, 114);
String chapter_array_name = "chapter_" + chapter_no;
String verse = sharedPreferencesVerse.getString(DateToday(),null);
if ( verse == null )
{
editor_verse.putString(DateToday(), getVerse(context,chapter_array_name));
editor_verse.apply();
}
int chapter_number = sharedPreferencesChapter.getInt(DateToday(),0);
if ( chapter_number == 0 )
{
editor_chapter.putInt(DateToday(),chapter_no);
editor_chapter.apply();
}
}
public String getVerseToday(String today,Context context)
{
sharedPreferencesVerse = context.getSharedPreferences(TODAY_VERSE, Context.MODE_PRIVATE);
return sharedPreferencesVerse.getString(today,"7. The Way of those on whom You have bestowed Your Grace, not (the way) of those who earned Your Anger (such as the Jews), nor of those who went astray (such as the Christians).");
}
public String getVerse(Context context,String chapter_array_name)
{
int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getPackageName());
String[] chapter = context.getResources().getStringArray(id);
int random_verse = GetRandom(1, chapter.length - 1);
return chapter[random_verse];
}
public String[] getChapterTodayContent(String today,Context context)
{
sharedPreferencesChapter = context.getSharedPreferences(TODAY_CHAPTER, Context.MODE_PRIVATE);
int chapter_no = sharedPreferencesChapter.getInt(today, 2);
String chapter_array_name = "chapter_" + chapter_no;
int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getApplicationContext().getPackageName());
return context.getResources().getStringArray(id);
}
public String getChapterTodayName(String today,Context context)
{
sharedPreferencesChapter = context.getApplicationContext().getSharedPreferences(TODAY_CHAPTER,Context.MODE_PRIVATE);
int chapter_no = sharedPreferencesChapter.getInt(today, 0);
String[] chapterName = context.getResources().getStringArray(R.array.chapters);
return chapterName[chapter_no - 1];
}
public String DateToday()
{
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("ddMMyyyy");
return df.format(c.getTime());
}
// Get quran verses in android
public String[] getQuranVerses(Context context) {
String[] whole_quran = new String[7000];
String[] current_chapter;
String chapterSize = "";
String[] chapter_names;
String chapter_array_name;
int total_verse = 0, verse_in_current_chapter, chapter_number;
chapter_names = context.getResources().getStringArray(R.array.chapters);
for (chapter_number = 1; chapter_number < 114; chapter_number++) {
// Grab each chapter containing verse from Quran
chapter_array_name = "chapter_" + chapter_number;
int id = context.getResources().getIdentifier(chapter_array_name, "array", context.getPackageName());
current_chapter = context.getResources().getStringArray(id);
for (verse_in_current_chapter = 1; verse_in_current_chapter < current_chapter.length - 1; verse_in_current_chapter++) {
whole_quran[total_verse] = current_chapter[verse_in_current_chapter] + "," + chapter_names[chapter_number - 1];
total_verse++;
}
chapterSize += chapter_number + ":" + chapter_names[chapter_number - 1] + ":" + current_chapter.length + "\n";
}
return whole_quran;
}
// public void search()
// {
// // Use search view on the top of your app
//
// search = (SearchView) findViewById(R.id.mySearchView);
// search.setQueryHint("Search Qur'an");
//
//// create a suggestion adapter for dropdown
// final String[] from = new String[] {"cityName"};
// final int[] to = new int[] {android.R.id.text1};
// mAdapter = new SimpleCursorAdapter(this,
// android.R.layout.simple_list_item_2,
// null,
// from,
// to,
// CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
//
// search.setSuggestionsAdapter(mAdapter);
//
// search.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
// #Override
// public boolean onSuggestionClick(int position) {
// // Your code here
//
//
// Cursor theCursor = (Cursor) mAdapter.getCursor();
// String selectedItem = theCursor.getString(position);
//// Toast.makeText(getBaseContext(), " on suggestion click position and item is" + position + selectedItem, Toast.LENGTH_LONG).show();
//
//
// startActivity(new Intent(getBaseContext(), MainActivity.class));
//
// return true;
// }
//
// #Override
// public boolean onSuggestionSelect(int position) {
// // Your code here
//// Toast.makeText(getBaseContext(), " on suggestion select position is" + position, Toast.LENGTH_LONG).show();
//
// startActivity(new Intent(getBaseContext(), MainActivity.class));
//
// return true;
// }
// });
//
// search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//
//
// #Override
// public boolean onQueryTextSubmit(String query) {
// startActivity(new Intent(getBaseContext(), MainActivity.class));
//
// return false;
// }
//
// #Override
// public boolean onQueryTextChange(String newText) {
// //
// dailyQuranMethods.populateAdapter(newText,getApplicationContext());
//
// return false;
// }
//
//
// });
//
//
//
// }
public void populateAdapter(String query, Context context, SimpleCursorAdapter mAdapter) {
String[] SUGGESTIONS = getQuranVerses(context);
final MatrixCursor c = new MatrixCursor(new String[]{BaseColumns._ID, "cityName"});
int j = 0;
int k = 0;
if (query.length() > 3) {
k = GetRandom(0, 60);
// Toast.makeText(getApplicationContext(),"K is " + k,Toast.LENGTH_LONG).show();
for (int i = 0; i < 6144; i++) {
if (SUGGESTIONS[i].toLowerCase().contains(query.toLowerCase()) && SUGGESTIONS[i].length() > 0) {
c.addRow(new Object[]{i, SUGGESTIONS[i]});
j++;
if (j > 100) {
break;
}
}
}
if (j == 0) {
c.addRow(new Object[]{0, "No results found."});
}
} else {
c.addRow(new Object[]{0, "Please enter at least 3 characters."});
c.addRow(new Object[]{1, "Please be patient, we have to find in more than 6,000 verses"});
}
mAdapter.changeCursor(c);
}
}
Calling getActivity() is fine, it will resolve to a Context. You don't need the full getActivity().getApplicationContext(). This may cause a problem since you're telling Android to use the context of the application instead of the current Activity. Someday you'll appreciate this.
Besides that, you NEED to create instance of dailyQuranMethods. In Java, you always need to create with new unless the object is static. This is good to remember.
Code sample:
public TodayVerse() {
DailyQuranMethods dailyQuranMethods = new DailyQuranMethods();
}
Good luck with Android Java...

Back menu to return from webview to app

I have an Webview which opens when i click on the actionbar item.
So i have Credits and Help, and when i click back it closes the app. Now, i want it not to close the app, but to get back to main screen (like app is launched)
Here's my main activity
package com.CPTeam.VselCalc;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import crakeron.vsel.calctest.R;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class VselcalculatortestActivity extends SherlockActivity {
private EditText freqbox1;
private EditText freqbox2;
private EditText freqbox3;
private EditText freqbox4;
private EditText freqbox5;
private EditText voltbox1;
private EditText voltbox2;
private EditText voltbox3;
private EditText voltbox4;
private EditText voltbox5;
private Spinner spinner;
public int freq1;
public int freq2;
public int freq3;
public int freq4;
public int freq5;
public int volt1;
public int volt2;
public int volt3;
public int volt4;
public int volt5;
public boolean stop=false;
public boolean freq4ornot=false;
public boolean freq5ornot=false;
//public String path;
/** Called when the activity is first created. */
private AutoUpdateApk aua;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
aua = new AutoUpdateApk(getApplicationContext());
ActionBar actionBar = getSupportActionBar();
//could be used to modify actionbar if needed
ChangeLog cl = new ChangeLog(this);
if (cl.firstRun())
cl.getLogDialog().show();
//cl.getFullLogDialog().show(); for testing
freqbox1 = (EditText) findViewById(R.id.freq1);
freqbox2 = (EditText) findViewById(R.id.freq2);
freqbox3 = (EditText) findViewById(R.id.freq3);
freqbox4 = (EditText) findViewById(R.id.freq4);
freqbox5 = (EditText) findViewById(R.id.freq5);
voltbox1 = (EditText) findViewById(R.id.volt1);
voltbox2 = (EditText) findViewById(R.id.volt2);
voltbox3 = (EditText) findViewById(R.id.volt3);
voltbox4 = (EditText) findViewById(R.id.volt4);
voltbox5 = (EditText) findViewById(R.id.volt5);
spinner = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spinner_choices, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
public void onItemSelected(AdapterView <?> adapter, View v, int pos, long lng) {
if (pos==0){
freq4ornot=false;
freq5ornot=false;
hide_row4();
hide_row5();
}
if (pos==1){
freq4ornot=true;
freq5ornot=false;
show_row4();
hide_row5();
}
if (pos==2){
freq4ornot=true;
freq5ornot=true;
show_row4();
show_row5();
}
}
public void onNothingSelected(AdapterView <?> arg0) {
//nothing FTM
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.Changelog:
new ChangeLog(this).getFullLogDialog().show();;
return true;
case R.id.Help:
WebView webview = new WebView(this);
setContentView(webview);
webview.loadUrl("file:///android_res/raw/help.html");
return true;
case R.id.Credits:
WebView webview1 = new WebView(this);
setContentView(webview1);
webview1.loadUrl("file:///android_res/raw/credits.html");
return true;
}
return true;
}
public void show_row4(){
freqbox4.setVisibility(View.VISIBLE);
findViewById(R.id.textView8).setVisibility(View.VISIBLE);
findViewById(R.id.TextView03).setVisibility(View.VISIBLE);
voltbox4.setVisibility(View.VISIBLE);
Log.d("VselCalc", "Showing row 4");
}
public void hide_row4(){
freqbox4.setVisibility(View.INVISIBLE);
findViewById(R.id.textView8).setVisibility(View.INVISIBLE);
findViewById(R.id.TextView03).setVisibility(View.INVISIBLE);
voltbox4.setVisibility(View.INVISIBLE);
Log.d("VselCalc", "Hiding row 4");
}
public void show_row5(){
freqbox5.setVisibility(View.VISIBLE);
findViewById(R.id.textView9).setVisibility(View.VISIBLE);
findViewById(R.id.TextView04).setVisibility(View.VISIBLE);
voltbox5.setVisibility(View.VISIBLE);
Log.d("VselCalc", "Showing row 5");
}
public void hide_row5(){
freqbox5.setVisibility(View.INVISIBLE);
findViewById(R.id.textView9).setVisibility(View.INVISIBLE);
findViewById(R.id.TextView04).setVisibility(View.INVISIBLE);
voltbox5.setVisibility(View.INVISIBLE);
Log.d("VselCalc", "Hiding row 5");
}
public void button_pressed(View button) {
voltbox1.setText("");
voltbox2.setText("");
voltbox3.setText("");
voltbox4.setText("");
voltbox5.setText("");
stop=false;
// 1. Grab values in textboxes freq1,2,3 (and 4 and 5, depending on Spinner value?) and store their values
grab_values(freq4ornot, freq5ornot);
// 2. Call calculate function with 3 (or 5) arguments
calculate(freq1, freq2, freq3, freq4, freq4ornot, freq5ornot);
// 3. call function to display each result in correct box, if stop=true, then all boxes will be displayed empty
display_volt(freq4ornot, freq5ornot);
if(stop==true) error_empty();
}
public void grab_values(boolean freq4ornot, boolean freq5ornot){
String freq1Value = freqbox1.getText().toString();//fetch what's in edittextbox and store it in a string
if(freq1Value.length()!=0){
freq1 = Integer.parseInt(freq1Value);//transform the string into an int and store it in our variable
}
if(freq1Value.length()==0){
stop=true;
freq1=0;
}
String freq2Value = freqbox2.getText().toString();
if(freq2Value.length()!=0){
freq2 = Integer.parseInt(freq2Value);//transform the string into an int and store it in our variable
}
if(freq2Value.length()==0){//check if user entered a value in box, otherwise causes crash
stop=true;
freq2=0;
}
String freq3Value = freqbox3.getText().toString();
if(freq3Value.length()!=0){
freq3 = Integer.parseInt(freq3Value);
}
if(freq3Value.length()==0){
stop=true;
freq3=0;
}
if (freq4ornot==true){
String freq4Value = freqbox4.getText().toString();
if(freq4Value.length()!=0){
freq4 = Integer.parseInt(freq4Value);
}
if(freq4Value.length()==0){
stop=true;
freq4=0;
}
if (freq5ornot==true){
String freq5Value = freqbox5.getText().toString();
if(freq5Value.length()!=0){
freq5 = Integer.parseInt(freq5Value);
}
if(freq5Value.length()==0){
stop=true;
freq5=0;
}
}}
}
public void calculate(int freq1,int freq2, int freq3, int freq4, boolean freq4ornot, boolean freq5ornot){
volt1 = formula(freq1);
volt2 = formula(freq2);
volt3 = formula(freq3);
if (freq4ornot==true){volt4 = formula(freq4);}
if (freq5ornot==true){volt5 = formula(freq5);}
}
public int formula(int freq){
int volt = ((freq/20)+2);
return volt;
}
public void display_volt (boolean freq4ornot,boolean freq5ornot){
if(stop==false){
voltbox1.setText(String.valueOf(volt1));
voltbox2.setText(String.valueOf(volt2));
voltbox3.setText(String.valueOf(volt3));
if(freq4ornot==true){voltbox4.setText(String.valueOf(volt4));}
if(freq5ornot==true){voltbox5.setText(String.valueOf(volt5));}
}
}
public void error_empty(){
Toast.makeText(getApplicationContext(), "Please enter a frequency in all the boxes", Toast.LENGTH_LONG).show();
/* For debug purposes
Toast.makeText(getApplicationContext(),"stop bool is " + stop, Toast.LENGTH_LONG).show();*/
}
//AUTODETECTION FUNCTIONS!!!
private int detected_freq1;
private int detected_freq2;
private int detected_freq3;
private int detected_freq4;
private int detected_freq5;
private String path;
public void auto_detect(View button){
stop=false;
freq4ornot=false;
freq5ornot=false;
//get the path string (for multiple device support) that leads to the cpu_freq file
{get_path();}
//read and process the file specified by path() and extract the frequencies
detect();
//fill the 4/5 freq boxes with the frequencies found
write_freq(detected_freq1,detected_freq2,detected_freq3,detected_freq4,detected_freq5);
if (stop==true){error_device();}
}
private void get_path(){
//find path for frequencies available
// for Defy (and milestone, and many other android devices) it is /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies
// for multiple devices support, probably store the paths in a table in the future
path="/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies";
//for testing, put a file called "Test" in the root directory of your phone to test behavior on 4/5 freqs
//path="/Test";
}
private void detect(){
String[] segs;
FileReader fstream;
long Read;
try {fstream = new FileReader(path);
Log.d("VselCalc_AutoD", "Opened '" + path + "' file correctly");
}
catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(), "Could not read " + path, Toast.LENGTH_LONG).show();
stop=true;
return;
}
BufferedReader in = new BufferedReader(fstream, 500);
String line;
try {
while ((line = in.readLine()) != null) {
Log.d("VselCalc_AutoD", "line read:"+ line);
segs = line.trim().split(" ");
Log.d("VselCalc_AutoD", "segs length: " + segs.length);
Read = Long.parseLong(segs[0]);
Log.d("VselCalc_AutoD", "Auto-Detect freq. Read1: " + Read);
detected_freq1= (int) Read/1000;
Read = Long.parseLong(segs[1]);
Log.d("VselCalc_AutoD", "Auto-Detect freq. Read2: " + Read);
detected_freq2= (int) Read/1000;
Read = Long.parseLong(segs[2]);
Log.d("VselCalc_AutoD", "Auto-Detect freq. Read3: " + Read);
detected_freq3= (int) Read/1000;
hide_row4();
hide_row5();
spinner.setSelection(0);
if(segs.length>=4){
Read = Long.parseLong(segs[3]);
Log.d("VselCalc_AutoD", "Freq4 exists. Auto-Detect freq. Read4: " + Read);
detected_freq4= (int) Read/1000;
freq4ornot=true;
spinner.setSelection(1);
Log.d("VselCalc_AutoD", "freq4ornot changed to true after auto-detect");
Log.d("VselCalc_AutoD", "freq5 or not: " + freq5ornot);
show_row4();
hide_row5();
}
if(segs.length>=5){
Read = Long.parseLong(segs[4]);
Log.d("VselCalc_AutoD", "Freq5 exists. Auto-Detect freq. Read5: " + Read);
detected_freq5= (int) Read/1000;
freq5ornot=true;
spinner.setSelection(2);
Log.d("VselCalc_AutoD", "freq5ornot changed to true after auto-detect");
show_row4();
show_row5();
}
}
} catch (IOException e) {
Log.e("readfile", e.toString());
}
return ;
}
public void write_freq(int fr1, int fr2, int fr3, int fr4, int fr5 ){
if(stop==false){
freqbox1.setText(String.valueOf(fr1));
freqbox2.setText(String.valueOf(fr2));
freqbox3.setText(String.valueOf(fr3));
if(freq4ornot==true){freqbox4.setText(String.valueOf(fr4));}
if(freq5ornot==true){freqbox5.setText(String.valueOf(fr5));}
Toast.makeText(getApplicationContext(), "Auto-Detection successful!", Toast.LENGTH_LONG).show();
}
}
public void error_device(){
Toast.makeText(getApplicationContext(), "Function may not be supported on your device. Please contact the developers", Toast.LENGTH_LONG).show();
}
}
I haven't added webview to layout/main.xml because it opens when i click on required actionbar item.
case R.id.Help:
WebView webview = new WebView(this);
setContentView(webview);
webview.loadUrl("file:///android_res/raw/help.html");
return true;
Targeted Android Version is 4.1
You should override onBackPressed() in your activity class.
public void onBackPressed ()
Since: API Level 5 Called when the activity has detected the user's
press of the back key. The default implementation simply finishes the
current activity, but you can override this to do whatever you want.
Copy this code in your activity, and do whatever you want in it.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
//this is where you start your activity
}
When back button is pressed the current intent/ activity is closed and returned to the previous intent/activity in the stack. Here You are creating a webview and just setting that as the content of your current activity. So when you press back, the activity is closed, which in turn closes the application as you don't have any previous intent/activity. Instead override onBackPressed and in there setContentView as main layout.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
setContentView(R.layout.main);
//Do other functions you want to do here
}

onListItemClick that shows description toast when title is clicked

not sure if I am on the correct section, but I needed help for my school project.
Currently I am doing a listview that display the titles of the latest school news, whenever I click any of the title, I want it to toast the description of the selected title correspondingly.
Anyone can help me on it? Thank you
package sp.buzz.rss;
import java.util.ArrayList;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.EventLogTags.Description;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import sp.buzz.rss.tools.*;
public class StringRss extends ListActivity {
HttpFetch a = new HttpFetch();
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String strOrg = a
.DownloadText("http://www.sp.edu.sg/wps/wcm/connect/lib-spws/Site-SPWebsite/?srv=cmpnt&source=library&cmpntname=MNU-MobileRSSFeed-SPBuzz-Shine");
int start = strOrg.indexOf("<title>");
int end = strOrg.indexOf("</title>");
int startdesc = strOrg.indexOf("<![CDATA[");
int enddesc = strOrg.indexOf("]]>");
int count = 0;
ArrayList<String> value = new ArrayList();
ArrayList<String> cData = new ArrayList();
String title = strOrg.substring(start + 7, end);
String description = strOrg.substring(startdesc + 9, enddesc);
// Toast.makeText(this, title, Toast.LENGTH_LONG).show();// first title
Toast.makeText(this, description, Toast.LENGTH_LONG).show();// first
// desc
// value.add(title);
// count++;
cData.add(description);
String newContent = strOrg.substring(end + 5);
String newDesc = strOrg.substring(enddesc + 3);
start = newContent.indexOf("<title>");
end = newContent.indexOf("</title>");
startdesc = newDesc.indexOf("<![CDATA[");
enddesc = newDesc.indexOf("]]>");
title = newContent.substring(start + 7, end);
description = newDesc.substring(startdesc + 9, enddesc);
// Toast.makeText(this, title, Toast.LENGTH_LONG).show();// second title
Toast.makeText(this, description, Toast.LENGTH_LONG).show();// second
// desc
value.add(title);
cData.add(description);
count++;
while (true) {
newContent = newContent.substring(end + 5);
newDesc = newDesc.substring(enddesc + 3);
start = newContent.indexOf("<title>");
end = newContent.indexOf("</title>");
startdesc = newDesc.indexOf("<![CDATA[");
enddesc = newDesc.indexOf("]]>");
if (start == -1 || end == -1) {
break;
} else if (startdesc == -1 || enddesc == -1) {
break;
}
title = newContent.substring(start + 7, end);
description = newDesc.substring(startdesc + 9, enddesc);
// Toast.makeText(this, description, Toast.LENGTH_LONG).show();//
// for
count++;
value.add(title);
cData.add(description);
/*
* Toast.makeText(this, "Value array: " + title, Toast.LENGTH_LONG)
* .show();// for debugging
*/
// Toast.makeText(this, description, Toast.LENGTH_LONG).show();//
// for
// description
}
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[count];
String[] desc = new String[count];
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
for (int i = 0; i < names.length; i++) {
names[i] = value.get(i);
}
for (int i = 0; i < desc.length; i++) {
desc[i] = cData.get(i).replaceAll("</P>", "\n")
.replaceAll("<P>", "");
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
}
static String title = "";
static String desc = "";
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
title = o.toString();
Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG)
.show();
}
}
You can replace the method protected void onListItemClick with by putting into onCreate the code below. If it isn't working.
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String title = ((TextView) view).getText();
Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG)
.show();
}});
Also I'm surprised that infinite while loop is working. You should do that part using threading otherwise the later parts of the method won't be reached.
String title = (String) parent.getItemAtPosition(position);
Toast.makeText(this, "You selected: " + title, Toast.LENGTH_LONG)
.show();

Struggling with a NullPointerException

Total newbie programmer here trying to make his first Android app. A simple countdown timer and a few other things and it was all working, but in order to try and fix an issue with the countdown timer I moved that section of code from within the Start Button onClick into the onCreate of the activity(or at least I think I have). In my head I think that means that the countdown timer is ready to run, but won't actually run until the user hits the Start Button.
Anyway, with the code below I'm getting a NullPointerException when the activity loads and I'm not sure where, or if anything I have done is remotely good programming (I've watched a lot of YouTube vids recently and got a lot of help from other questions here).
Any help would be very well received :)
package com.asurya.hulktimer;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class main extends Activity {
long starttime = 180000;
long count = 1000;
long timechange = 30000;
int missionpoints = 0;
boolean isPaused = false;
boolean clockrunning = false;
Context context = getApplicationContext();
CharSequence text = "Clock is running - create some pause code";
int duration = Toast.LENGTH_LONG;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.asurya.hulktimer.R.layout.main);
// THIS SECTION ENABLES THE FEEDBACK FOR ALL THE BUTTONS
final Vibrator vibe = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
// THIS SECTION DEFINES THE FONT FOR ALL THE OBJECTS IN THE VIEW
final Button but_start = (Button) findViewById(com.asurya.hulktimer.R.id.but_start);
Typeface font = Typeface.createFromAsset(getAssets(), "CASLANTR.TTF");
but_start.setTypeface(font);
final Button but_reset = (Button) findViewById(com.asurya.hulktimer.R.id.but_reset);
but_reset.setTypeface(font);
final TextView txt = (TextView) findViewById(com.asurya.hulktimer.R.id.timer);
txt.setText(formatTime(starttime));
txt.setTypeface(font);
final TextView txt_mt_1 = (TextView) findViewById(com.asurya.hulktimer.R.id.lbl_missiontally_1);
txt_mt_1.setTypeface(font);
final TextView txt_mt_2 = (TextView) findViewById(com.asurya.hulktimer.R.id.lbl_missiontally_2);
txt_mt_2.setTypeface(font);
final TextView txt_mt_value = (TextView) findViewById(com.asurya.hulktimer.R.id.lbl_mt_value);
txt_mt_value.setTypeface(font);
final TextView txt_cp_value = (TextView) findViewById(com.asurya.hulktimer.R.id.lbl_cp_value);
txt_cp_value.setTypeface(font);
final Button but_add_time = (Button) findViewById(com.asurya.hulktimer.R.id.but_add);
but_add_time.setTypeface(font);
final Button but_minus_time = (Button) findViewById(com.asurya.hulktimer.R.id.but_minus);
but_minus_time.setTypeface(font);
final Button but_generate_cp = (Button) findViewById(com.asurya.hulktimer.R.id.but_generate_cp);
but_generate_cp.setTypeface(font);
final Button but_mp_add = (Button) findViewById(R.id.but_mp_add);
but_mp_add.setTypeface(font);
final Button but_mp_minus = (Button) findViewById(com.asurya.hulktimer.R.id.but_mp_minus);
but_mp_minus.setTypeface(font);
final Button but_mp_reset = (Button) findViewById(com.asurya.hulktimer.R.id.but_mp_reset);
but_mp_reset.setTypeface(font);
{
// THIS SECTION IS THE COMMAND POINTS CODE
final MediaPlayer mp = MediaPlayer.create(this, R.raw.generate);
Button but_generate_cp1 = (Button) findViewById(com.asurya.hulktimer.R.id.but_generate_cp);
but_generate_cp1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
mp.start();
final Random random = new Random();
int mycps = random.nextInt(6);
final int myCommandPoints = mycps + 1;
txt_cp_value.setText("" + String.valueOf(myCommandPoints));
}
});
}
// THIS SECTION IS THE COUNTDOWN TIMER
final MediaPlayer oneminrem = MediaPlayer.create(this, R.raw.ping);
final CountDownTimer gameclock = new CountDownTimer(starttime, count) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
txt.setText("" + formatTime(millisUntilFinished));
long oneMinuteRemaining = millisUntilFinished /1000;
if (oneMinuteRemaining == 60){
oneminrem.start();
}
if (oneMinuteRemaining == 30){
oneminrem.start();
}
if (oneMinuteRemaining == 15){
oneminrem.start();
}
if (oneMinuteRemaining == 10){
oneminrem.start();
}
if (oneMinuteRemaining == 9){
oneminrem.start();
}
if (oneMinuteRemaining == 8){
oneminrem.start();
}
if (oneMinuteRemaining == 7){
oneminrem.start();
}
if (oneMinuteRemaining == 6){
oneminrem.start();
}
if (oneMinuteRemaining == 5){
oneminrem.start();
}
if (oneMinuteRemaining == 4){
oneminrem.start();
}
if (oneMinuteRemaining == 3){
oneminrem.start();
}
if (oneMinuteRemaining == 2){
oneminrem.start();
}
if (oneMinuteRemaining == 1){
oneminrem.start();
}
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
txt.setText("00:00");
but_start.setText("Start");
clockrunning = false;
}
};
// THIS SECTION IS THE TIMER BUTTONS
Button but_start1 = (Button) findViewById(R.id.but_start);
but_start1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
if (clockrunning = false) {
gameclock.start();
}
if (clockrunning = true) {
// Display a Toast message to confirm code working.
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
Button but_reset1 = (Button) findViewById(R.id.but_reset);
but_reset1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
if (clockrunning == true){
}
}
});
//THIS SECTIONS IS THE BUTTONS WHICH ADD OR SUBTRACT TIME FROM THE STARTING TIME
Button but_add1 = (Button) findViewById(R.id.but_add);
but_add1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
if (clockrunning == false) {
starttime = starttime + timechange;
txt.setText(formatTime(starttime));
}
}
});
Button but_minus1 = (Button) findViewById(R.id.but_minus);
but_minus1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
if (clockrunning == false) {
starttime = starttime - timechange;
txt.setText(formatTime(starttime));
}
}
});
//THIS SECTION HANDLES THE MISSIONS POINTS CODE
txt_mt_value.setText("" + String.valueOf(missionpoints));
Button but_missionpoint_add = (Button) findViewById(R.id.but_mp_add);
but_missionpoint_add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
missionpoints = missionpoints + 1;
txt_mt_value.setText("" + String.valueOf(missionpoints));
}
});
Button but_missionpoint_minus = (Button) findViewById(R.id.but_mp_minus);
but_missionpoint_minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
missionpoints = missionpoints - 1;
txt_mt_value.setText("" + String.valueOf(missionpoints));
}
});
Button but_missionpoints_reset = (Button) findViewById(R.id.but_mp_reset);
but_missionpoints_reset.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
vibe.vibrate(50);
missionpoints = 0;
txt_mt_value.setText("" + String.valueOf(missionpoints));
}
});
}
/* (non-Javadoc)
* #see android.app.Activity#finish()
*/
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
}
public String formatTime(long millis) {
// String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String secondsD = String.valueOf(seconds);
String minutesD = String.valueOf(minutes);
if (seconds < 10)
secondsD = "0" + seconds;
if (minutes < 10)
minutesD = "0" + minutes;
String output = minutesD + " : " + secondsD;
return output;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.Info:
Intent myInfoMenuIntent = new Intent(main.this, Info.class);
startActivity(myInfoMenuIntent);
return true;
case R.id.Credits:
Intent myCreditMenuIntent = new Intent(main.this, Credits.class);
startActivity(myCreditMenuIntent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Think about making your UI elements (e.g. txt_cp_value) member variables of the class and then assign them in the onCreate method. That way they'll be accessible from the anonymous OnClickListener. From what I can see, txt_cp_value.setText("" + String.valueOf(myCommandPoints)); could be the culprit.
Have you got the stack trace?
A null pointer exception in a line of type
A.B.C.D
means that either
A is null
or A.B is null
or A.B.C is null
Something at the left of a point is null.
So provide intermedite variables and print them in console to detect which is null.
Regards,
Stéphane
"A simple countdown timer and a few other things and it was all working, but in order to try and fix an issue with the countdown timer I moved that section of code from within the Start Button onClick into the onCreate of the activity"
If this is true, then most likely the code which you moved to the onCreate method tries to use something which is not initialized in the onCreate method, but it was initialized in the start button onClick method. Look for something like this in your code.
About the code. This is far from efficient:
if (oneMinuteRemaining == 60){
oneminrem.start();
}
if (oneMinuteRemaining == 30){
oneminrem.start();
}
You should use 'else if' after the first 'if' instead.
Fixed it
Context context = getApplicationContext();
CharSequence text = "Clock is running - create some pause code";
int duration = Toast.LENGTH_LONG;
Was the guilty code. Relocated it inside the button onClick listener. That's just temporary code for testing something anyway.
Thanks for all the help again guys. I now know more about Java and stack traces than I did yesterday :)

Categories

Resources