onListItemClick that shows description toast when title is clicked - java

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();

Related

Remove string after second colon in Java

I would like to remove the string after the second colon and add a new string behind.
I have a maker when clicking on a marker I add the string using ALertDialog on the marker title so I can get those value to the process for a text file. But if I select that marker again I want to remove that text after colon so I don't add duplicate string again.
I checked this link but it uses a regular expression and I don't have any experience with that.
My String = W:3:ER1,ER2,ER3,,,,
Output = W:3
I would like to remove the string after the second colon so I can attach my string
Here is my onMarkerClick
#Override
public boolean onMarkerClick(final Marker marker) {
final String[] title = {marker.getTitle()};
Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
R.drawable.blue_dot), 15, 15, false);
final String[] selectedItems = {"", "", "", "", ""};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Enable Relays");
// add a checkbox list
final String[] relays = {"Relay 1", "Relay 2", "Relay 3", "Relay 4", "Implement"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems[which] = "ER" + (which + 1);
} else if (!isChecked) {
// Else, if the item is already in the array, remove it
selectedItems[which] = "";
}
Toast.makeText(MainActivity.this, "" + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// title[0] += ":" + selectedItems[0] + "," + selectedItems[1] + "," + selectedItems[2] + "," + selectedItems[3] + "," + selectedItems[4];
int commas = 0;
for (int i = 0; i < title[0].length(); i++) {
if (title[0].charAt(i) == ',') commas++;
}
if (!title[0].contains("ER1") && commas <= 4)
title[0] += ":" + selectedItems[0];
if (!title[0].contains("ER2") && commas <= 4)
title[0] += "," + selectedItems[1];
if (!title[0].contains("ER3") && commas <= 4)
title[0] += "," + selectedItems[2];
if (!title[0].contains("ER4") && commas <= 4)
title[0] += "," + selectedItems[3];
if (!title[0].contains("ER5") && commas <= 4)
title[0] += "," + selectedItems[4];
marker.setTitle(title[0]);
marker.showInfoWindow();
Toast.makeText(MainActivity.this, "" + title[0], Toast.LENGTH_LONG).show();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
First we split on the last : to get the title.
Then we parse on , from the last : to get items and we filter out empty ones.
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String raw = "W:3:ER1,ER2,ER3,,,,";
String title = raw.substring(0, raw.lastIndexOf(":"));
String[] selectedItems = raw.substring(raw.lastIndexOf(":")+1).split(",");
List<String> items = Arrays.asList(selectedItems).stream().filter(str ->
! "".equals(str)
).collect(Collectors.toList());
System.out.println("Title "+ title);
System.out.println("Items "+ items);
}
}
Prints
Title W:3
Items [ER1, ER2, ER3]
Edit 1 : Should handle single colon
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String raw = "W:3";
List<String> items;
String title;
if (raw.replaceAll("[^:]", "").length() > 1) { // String with every :
title = raw.substring(0, raw.lastIndexOf(":"));
String[] selectedItems = raw.substring(raw.lastIndexOf(":") + 1).split(",");
items = Arrays.asList(selectedItems).stream().filter(str ->
!"".equals(str)
).collect(Collectors.toList());
} else {
title = raw;
items = null;
}
System.out.println("Title "+ title);
System.out.println("Items "+ items);
}
}
And prints for raw = "W:3";
Title W:3
Items null
I found the trick to remove string after the second colon.
First, find the position for the second colon. Then remove the string after that position.
Here the method for finding the position
private static int findSecondColonPosition(String s) {
int result = -1;
int dotsToFind = 2;
char[] ca = s.toCharArray();
for (int i = 0; i < ca.length; ++i) {
if (ca[i] == ':') --colonsToFind;
if (dotsToFind == 0) return i;
}
return result;
}
Here my updated onMarkerClick code
#Override
public boolean onMarkerClick(final Marker marker) {
final String[] title = {marker.getTitle()};
Bitmap smallDot = Bitmap.createScaledBitmap(getBitmapFromVectorDrawable(getApplicationContext(),
R.drawable.blue_dot), 15, 15, false);
final String[] selectedItems = { "", "", "", ""};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Enable Relays");
// add a checkbox list
final String[] relays = {"Relay 2", "Relay 3", "Relay 4", "Implement"};
builder.setMultiChoiceItems(relays, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
selectedItems[which] = "ER" + (which + 2);
} else if (!isChecked) {
// Else, if the item is already in the array, remove it
selectedItems[which] = "";
}
Toast.makeText(MainActivity.this, "" + Arrays.toString(selectedItems), Toast.LENGTH_LONG).show();
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int secoundColonPosition = findSecondColonPosition(title[0]);
if (secoundColonPosition > 0) {
System.out.println("title after remove: " + title[0].substring(0, secoundColonPosition));
title[0] = title[0].substring(0, secoundColonPosition);
} else {
System.out.println("ERROR: there is not a 2nd colon in " + title[0]);
}
title[0] += ":" + selectedItems[0] + "," + selectedItems[1] + "," + selectedItems[2] + "," + selectedItems[3];
marker.setTitle(title[0]);
marker.showInfoWindow();
Toast.makeText(MainActivity.this, "" + title[0], Toast.LENGTH_LONG).show();
}
}).setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
// if (isEnable()) {
// title += ":Enable_Implement";
// marker.setTitle(title);
// marker.setIcon(BitmapDescriptorFactory.fromBitmap(smallDot));
// setEnable(false);
// setDisable(true);
// programStatusTextView.setText("Choose a stop actuation point");
// } else if (isDisable()) {
// title += ":Disable_Implement";
// marker.setTitle(title);
// marker.setIcon(BitmapDescriptorFactory.fromBitmap(smallDot));
// setDisable(false);
// programStatusTextView.setText("");
// }
return true;
}

ERROR java.lang.ArrayIndexOutOfBoundsException: length=5; index=5

I'm working on Android Studio Project for my university (app calendar and more), and one of the functionalities is touch in a day of a calendar (CalendarView), display a layout for add event and later the event is saved in a SQLITE, (in another activity is where the list of events is displayed) the problem is when I want to delete an event (java.lang.ArrayIndexOutOfBoundsException: length=5; index=5).
In Viewevents eliminar(String dato) is the code with error, How do I fix the issue? Thanks.
View events:
public class ViewEventsActivity extends AppCompatActivity implements AdapterView.OnItemLongClickListener {
//al mantener la wea apretada
private SQLiteDatabase db;
private ListView listView;
private ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_events);
listView=(ListView) findViewById(R.id.ltvListaEventos);
listView.setOnItemLongClickListener(this);
Bundle bundle= getIntent().getExtras();
int dia,mes,anio;
dia=mes=anio=0;
dia=bundle.getInt("dia");
mes=bundle.getInt("mes");
anio=bundle.getInt("anio");
String cadena= dia+" - "+ mes + " - "+ anio;
BDSQLite bd= new BDSQLite(getApplicationContext(), "eventos", null,1);
db= bd.getReadableDatabase();
String sql="select * from eventos where fechadesde='"+cadena+"'";
Cursor c;
String nombre,fechadesde,horadesde,fechahasta,horahasta,descripcion,ubicacion;
try {
c=db.rawQuery(sql,null);
arrayAdapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
if(c==null||c.getCount()==0) {
Toast.makeText(getBaseContext(), "No hay eventos disponibles", Toast.LENGTH_LONG).show();
}
if(c.moveToFirst()){
do {
nombre=c.getString(1);
ubicacion=c.getString(2);
fechadesde=c.getString(3);
horadesde=c.getString(4);
fechahasta=c.getString(5);
horahasta=c.getString(6);
descripcion=c.getString(7);
arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);
} while(c.moveToNext());
listView.setAdapter(arrayAdapter);
}
}catch (Exception ex) {
Toast.makeText(getApplication(), "Error: "+ex.getMessage(), Toast.LENGTH_SHORT).show();
this.finish();
}
}
private void eliminar(String dato){
String []datos= dato.split(", ");
String sql="delete from eventos where nombreEvento='"+datos[0]+"' and" +
" ubicacion='"+datos[1]+"' and fechadesde='"+datos[2]+"' and " +
"horadesde='"+datos[3]+"' and fechahasta='"+datos[4]+"' and horahasta='"+datos[5]+"' and descripcion='"+datos[6];
try {
arrayAdapter.remove(dato); //eliminar del menĂº
listView.setAdapter(arrayAdapter);
db.execSQL(sql);
Toast.makeText(getApplication(),"Evento eliminado",Toast.LENGTH_SHORT).show();
}catch (Exception ex){
Toast.makeText(getApplication(),"Error:"+ ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder builder= new AlertDialog.Builder(this);
CharSequence []items= new CharSequence[2];
items[0]="Eliminar Evento";
items[1]="Cancelar";
builder.setTitle("Eliminar evento")
.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(i==0){
//eliminar evento
eliminar(adapterView.getItemAtPosition(i).toString());
}
}
});
AlertDialog dialog= builder.create();
dialog.show();
return false;
}
}
BDSQlite:
public class BDSQLite extends SQLiteOpenHelper {
private String sql = "create table eventos(" +
"idEvento int identity,"+
"nombreEvento varchar(40)," +
"ubicacion varchar(60)," +
"fechadesde date,"+
"horadesde time,"+
"fechahasta date,"+
"horahasta time," +
"descripcion varchar(60))";
Add event activity
public class AddActivity extends AppCompatActivity implements View.OnClickListener {
private EditText nombreEvento, ubicacion, fechadesde, horadesde, fechahasta, horahasta;
private EditText descripcion;
private Button guardar, cancelar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
nombreEvento = (EditText) findViewById(R.id.edtNombreEvento);
ubicacion = (EditText) findViewById(R.id.edtUbicacion);
fechadesde = (EditText) findViewById(R.id.edtFechaDesde);
fechahasta = (EditText) findViewById(R.id.edtFechaHasta);
horadesde = (EditText) findViewById(R.id.edtHorainicio);
horahasta = (EditText) findViewById(R.id.edtHoraHasta);
descripcion = (EditText) findViewById(R.id.edtDescripcion);
Bundle bundle = getIntent().getExtras();
int dia = 0, mes = 0, anio = 0;
dia=bundle.getInt("dia");
mes=bundle.getInt("mes");
anio=bundle.getInt("anio");
fechadesde.setText(dia + " - " + mes + " - " + anio);
fechahasta.setText(dia + " - " + mes + " - " + anio);
guardar = (Button) findViewById(R.id.btnguardar);
cancelar = (Button) findViewById(R.id.btncancelar);
guardar.setOnClickListener(this);
cancelar.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == guardar.getId()) {
//guardar datos cajas de texto
BDSQLite bd = new BDSQLite(getApplication(), "eventos", null, 1);
SQLiteDatabase db = bd.getWritableDatabase();
String sql = "insert into eventos" +
"(nombreEvento, ubicacion, fechadesde, horadesde, fechahasta, horahasta," +
"descripcion) values('" +
nombreEvento.getText()+
"','"+ ubicacion.getText()+
"','" +fechadesde.getText()+
"','" + horadesde.getText()+
"','"+fechahasta.getText()+
"','"+horahasta.getText()+
"','"+descripcion.getText();
try {
db.execSQL(sql);
nombreEvento.setText("");
ubicacion.setText("");
fechadesde.setText("");
fechahasta.setText("");
horadesde.setText("");
horahasta.setText("");
descripcion.setText("");
Toast.makeText(getBaseContext(), "Evento guardado", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplication(),"Error"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
} else {
this.finish();
return;
}
}
}
ERROR:
java.lang.ArrayIndexOutOfBoundsException: length=5; index=5
at com.example.niikoo.fondocelular.ViewEventsActivity.eliminar(ViewEventsActivity.java:87)
at com.example.niikoo.fondocelular.ViewEventsActivity.access$000(ViewEventsActivity.java:17)
at com.example.niikoo.fondocelular.ViewEventsActivity$1.onClick(ViewEventsActivity.java:116)
EDIT: The code with the structure of sql and datos, how i fix the error:(
Exception line (java.lang.ArrayIndexOutOfBoundsException: length=5; index=5) clearly mentions that you are Trying to get index=5but the length of the dato is 5(length=5).
So, use only proper index i.e. index 0 to 4. OR Make sure that enough indexes exists to access.
Note: You have used dato.split(", ");. Try with dato.split(",");. May be the problem is with pattern of splitter.
It looks like your String dato which you are splitting by commas to an array may not be the length that you think. The error is showing 5 items in the array, so the greatest index you can access in that case would be datos[4] since arrays are 0-based.
Debug your array after you split:
String []datos= dato.split(", ");
Check the input of this method, it's not in the code.
eliminar(adapterView.getItemAtPosition(i).toString());
The error you get occurs because the array you get after splitting the String has only 5 elements (4 commas):
private void eliminar(String dato) {
String []datos= dato.split(", ");
...
But then you try to get the 6th (index 5) and 7th (index 6) elements from that array:
datos[5]+"' and descripcion='"+datos[6];
There are no such elements, therefore you get this ArrayIndexOutOfBoundsException error.
To fix, try to find the input of your adapterView.
EDIT: In this line 2 Strings appear to be empty:
arrayAdapter.add(nombre+", "+ubicacion+", "+fechadesde+", "+horadesde+", "+fechahasta+", "+horahasta+", "+descripcion);
Hence, when you get a ", , " and split it with split(", ") it doesn't count the "" String and you get less items in the resulting array, which leads to the error.

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...

How to clear all items in a ListView while using List Adapter onTextChange?

I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back

A way to save Arraylist on device?

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!

Categories

Resources