So, I'm debugging my project in Android Studio, it's just a tutorial I'm doing, and I have a Handler I'm trying to use.
I can step over all the code in the run part. Then when I get out of run it steps into Handler.java and android studio has all these errors marked in in the Handler.java file and the program crashes.
I'm pretty sure Handler is part of the jdk and when added Handler to my activity it imported the file automatically. I've invalidated caches and cleaned the project. I've ran into this problem with a number of tutorials but never found an answer on how to solve.
In the other cases I uninstalled and reinstalled android studio but that didn't help me out.
This is the code that eventually steps into Handler.java but that is not the problem. The problem is that Android Studio says there are errors throughout Handler.java. I'm using Android Studio 2.0 but I've run into this with other versions too with other jdk java files.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Cursor c = sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF", null);
Log.d("arindam", "c count"+ c.getCount());
if (c.getCount() == 0){
sqLite.execSQL("INSERT INTO USER_PREF (CITY_NAME, VOICE_ON, NOTIF)" +
" VALUES('NONE', 'Y', 'Y')");
}
c.close();
Cursor d = sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF", null);
Log.d("arindam", "d count" + d.getCount());
if (d.moveToFirst()){
Log.d("arindam", "d NONE" + d.getString(0));
if (d.getString(0).equals("NONE")){
Intent intent = new Intent(StartScreen.this, CityScreen.class);
startActivity(intent);
}
else {
//Intent intent = new Intent(StartScreen.this, HomeScreen.this);
//startActivity(intent);
}
d.close();
finish();
}
}
},1000);
This is the logcat.
11-24 22:05:47.270 1740-1740/com.example.andrewspiteri.basket E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.andrewspiteri.basket, PID: 1740
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.andrewspiteri.basket/com.example.andrewspiteri.basket.CityScreen}: java.lang.RuntimeException: native typeface cannot be made
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.RuntimeException: native typeface cannot be made
at android.graphics.Typeface.<init>(Typeface.java:175)
at android.graphics.Typeface.createFromAsset(Typeface.java:149)
at com.example.andrewspiteri.basket.CityScreen.onCreate(CityScreen.java:26)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
This is CityScreen.java, the program doesn't even get there.
public class CityScreen extends ActionBarActivity {
SQLiteDatabase sqLite;
Spinner city_spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_screen);
Typeface type = Typeface.createFromAsset(getAssets(),"fonts/books.TTF");
//section is to hide the action bar.
ActionBar actionBar = getActionBar();
actionBar.hide();
//Ideally SQL should be handled in a separate helper,
//but for ease of understanding to start
//off, I have kept the code here.
sqLite = this.openOrCreateDatabase("basketbuddy",MODE_PRIVATE, null);
Cursor c = sqLite.rawQuery("SELECT CITY_NAME FROM CITY_LIST",null);
//ideally at least 1 city should be there in city_name
//As I have already synced this with the serve in
//StartScreen.java
if (c.getCount() == 0){
Toast.makeText(getApplicationContext(), "Oh ho..." +
"Some unexpected problem. Please restart the application",
Toast.LENGTH_LONG);
}
TextView city_selection = (TextView) findViewById(R.id.SelectCityText);
city_selection.setTypeface(type);
//Defining the array that will hold the City Names
String[] city_name_db = new String[(c.getCount()+1)];
//By default, the first entry for city list is "Choose City"
//We will understand who this is necessary later.
city_name_db[0] = "Choose City";
//Moving the city names from sqlite to an array city_name_db
if (c.moveToFirst()){
int count = 1;
do {
city_name_db[count] = c.getString(0);
count++;
}
while (c.moveToNext());{
}
//creating an ArrayAdapter for the spinner and then
//associating the ArrayAdapter to the spinner
ArrayAdapter<String> aa = new ArrayAdapter<String>
(getApplicationContext(),R.layout.spinner_item,city_name_db);
city_spinner = (Spinner) findViewById(R.id.spinner1);
city_spinner.setAdapter(aa);
//There is an inherent problem with Spinners. Lets
//assume that there are 3 cities Delhi, Gurgaon, Noida.
//The moment I populate these 3 cities to the spinner,
//by default Delhi will get selected as this is the first
//entry. OnItemSelectedListener will get triggered
//immediately with Delhi as selection and the code will
//proceed. Net net, even the default first value is
//taken as an ItemSelected trigger. The way to bypass
//this is to add a default value 'Choose City' in the
// ArrayAdapter list. Then inside the onItemSelected method,
//ignore if 'Choose City' has been selected.
//SetOnItemSelectedListener listens for any change in item
//if found then it will call onItemSelectedListener listens
//listens for any change in item selected, if found
//then it will call onItemSelected method.
city_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView
parent, View view,
int position, long id) {
if (parent.getItemAtPosition(position).equals("Choose City")){
//do nothing
}
else {
//save selected city as a default city
//for shopping. This city selection is saved in DB
//We may even decide to send to send this data to server,
// however in this example, we are not doing so.
String city_name = city_spinner.getSelectedItem().toString();
Cursor c = sqLite.rawQuery("SELECT CITY_NAME FROM USER_PREF",
null);
if (c.getCount() == 0){sqLite.execSQL("insert into USER_PREF"+"" +
"(CITY_NAME, VOICE_ON) VALUES ('" + city_name +
"', 'Y', 'Y')");
}
if (c.moveToFirst()){
sqLite.execSQL("update USER_PREF set CITY_NAME = '" +
city_name + "'");
}
//Intent intent = new Intent(CityScreen.this, HomeScreen.class);
//startActivity(intent);
sqLite.close();
finish();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}
Related
I have a problem with SQliteDatabase/OpenHelper/AssetHelper that is difficult to fix because I cannot replicate the error that many of my app users are having on my devices or on any android studio emulated devices, so this code I'm about to show you works for me, but not some others and I don't know why.
My users sometimes get an indexoutofboundsexception (I believe) when my app takes a value from a List that is populated from a database (in the assets folder). So it seems the database is not loading properly. The problem might be related to the context I'm passing when I get an instance of the DatabaseAccess class DBProgressAccess in OnResume lifecycle callback of the Fragment.
I haven't tried much to fix the issue only because the crash so rarely occurs (just once on my android 6.0 phone), but I'm getting reports from google of frequent crashing for other android devices (up to and including android 6.0).
The stack trace I have for the crashes comes from google developers console.
I have a fragment that loads at the startup of the app. In its showSets12() method called from onResume() (where I see the indexoutofbounds error) I access a database of the users scores:
private void showSets12()
{
DBProgressAccess dbProgressAccess = DBProgressAccess.getInstance(getActivity());
dbProgressAccess.openUserProgressDb();
dbProgressAccess.getDayValues();
int scoreToday = dbProgressAccess.getScores().get(0); <--I think the error comes from this
...
dbProgressAccess.closeUserProgressDb();
}
In the public DBProgressAccess class I have:
public class DBProgressAccess {
private SQLiteOpenHelper openHelper;
private SQLiteDatabase database;
private static DBProgressAccess instance;
private List<String> dates;
private List<Integer> scores;
private List<String> times;
public static final String TABLE_NAME = "UserProgress";
public List<Integer> getScores() {return scores;}
private DBProgressAccess(Context context) {
this.openHelper = new DBProgressHandler(context);
}
public static DBProgressAccess getInstance(Context context)
{
Log.d(TAG, "getInstance");
if(instance == null) {
instance = new DBProgressAccess(context);
}
return instance;
}
/**
* Open the database connection.
*/
public void openUserProgressDb() {
Log.d(TAG, "openUserProgress");
this.database = openHelper.getWritableDatabase();
}
/**
* Is todays date included in the database? If not, create it and search the database to populate lists for times and scores
*/
public void getDayValues()
{
if (checkIfDateExists()) {
Cursor cursor = searchDayProgress();
searchDatabase(cursor);
}
else
{
createDayEntry();
Cursor cursor = searchDayProgress();
searchDatabase(cursor);
}
}
/**
* Check to see if there is a record in the database for today
*/
public boolean checkIfDateExists()
{
Cursor cursor = searchDayProgress();
if(cursor.getCount() <= 0)
{
cursor.close();
return false;
}
cursor.close();
return true;
}
/**
* Insert todays date into the database
*/
private void createDayEntry()
{
Date today = Calendar.getInstance().getTime();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String todayString = formatter.format(today);
int score = 0;
String time = "0:00:0";
ContentValues cv = new ContentValues();
cv.put("date", todayString);
cv.put("score", score);
cv.put("time", time);
database.insert(TABLE_NAME, null, cv);
}
/**
* Find the database record for today
*/
private Cursor searchDayProgress() {
String whereQuery = "SELECT * FROM UserProgress WHERE date = date('now')";
Log.d(TAG, "searchWeekProgress " + whereQuery);
return database.rawQuery(whereQuery, null);
}
/**
* Populate lists of time, date and progress taken from the database
*/
public void searchDatabase(Cursor cursor)
{
List<String> listDate = new ArrayList<>();
List<Integer> listUserProgress = new ArrayList<>();
List<String> listTime = new ArrayList<>();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
listDate.add(cursor.getString(cursor.getColumnIndex("date")));
listUserProgress.add(cursor.getInt(cursor.getColumnIndex("score")));
listTime.add(cursor.getString(cursor.getColumnIndex("time")));
cursor.moveToNext();
}
cursor.close();
setDates(listDate);
setScores(listUserProgress);
setTimes(listTime);
}
private void setDates(List<String> dates) {this.dates = dates;}
private void setScores(List<Integer> scores) {this.scores = scores;}
private void setTimes(List<String> times) {this.times = times;}
}
I believe the List<string> variables turn out to be empty.
I wish I could put in more specific code but the google dev console stack trace is unclear.
The error I get is from the google developers console, not android studio, since I cannot replicate the issue on my devices or any emulated devices.
java.lang.RuntimeException:
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3573)
at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:3613)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2862)
at android.app.ActivityThread.-wrap12 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1574)
at android.os.Handler.dispatchMessage (Handler.java:110)
at android.os.Looper.loop (Looper.java:203)
at android.app.ActivityThread.main (ActivityThread.java:6364)
at java.lang.reflect.Method.invoke (Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1076)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:937)
Caused by: java.lang.IndexOutOfBoundsException:
at java.util.ArrayList.get (ArrayList.java:411)
at org.ieltstutors.academicwordlist.AcademicWordListFragment.showSets12 (AcademicWordListFragment.java)
at org.ieltstutors.academicwordlist.AcademicWordListFragment.access$000 (AcademicWordListFragment.java)
or .access$200 (AcademicWordListFragment.java)
or .drawCircularLockedProgress (AcademicWordListFragment.java)
or .onCreateView (AcademicWordListFragment.java)
or .openCloseSet (AcademicWordListFragment.java)
or .showCircularScores (AcademicWordListFragment.java)
or .showScores (AcademicWordListFragment.java)
or .updateScores (AcademicWordListFragment.java)
at org.ieltstutors.academicwordlist.AcademicWordListFragment.onResume (AcademicWordListFragment.java)
Unfortunately, that is all the information I have on the error.
So the IndexOutOfBoundsException comes from showSets12.
Could the error be from using the wrong context for getInstance? Or maybe from getWriteableDatabase?
Why might the database be accessed correctly some times but not other times? I remember that when the app crashed on my phone when the app started up, I immediately tried to open the app on my friend's phone, but it crashed also, having never crashed before on either. Coincidence?
Any help is greatly appreciated. Thanks!
The fragments onResume() or onPause() will be called only when the Activities onResume() or onPause() is called. They are tightly coupled to the Activity. if you want to do something when your fragment added to activity you can use OnAttach() or other fragment lifecycles
Read this to understand the Fragment Lifecycle
I have lists of color variations of a product in the ListView . Each list color variation has an EditText. I want to try to make the validation process orders when my button clicked.
This My Code:
btnOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int count = listView.getAdapter().getCount();
String[] listData = new String[count];
int[] listData2 = new int[count];
int sum = 0;
try {
for (int i = 0; i < count; i++) {
View quantity=listView.getChildAt(i);
if (quantity.findViewById(R.id.quantityOrder) != null){
EditText quantityOrder = (EditText) quantity.findViewById(R.id.quantityOrder);
listData[i] = quantityOrder.getText().toString();
listData2[i] = Integer.parseInt(quantityOrder.getText().toString()); // set edittext to int
sum += listData2[i];
jsonObject.put("params_"+i,listData[i]); // put to params for volley request
}
}
if (sum < 1) {Toast.makeText(getApplicationContext(),
"Sorry, you need to fill Order Quantity", Toast.LENGTH_SHORT) // validation input if edittext empty
.show();} else {
Log.d(TAG, jsonObject.toString()); }
} catch (JSONException e) {
e.printStackTrace();
}
}
});
My app get force close. here the error code
09-25 23:01:05.679 32623-32623/id.nijushop.ikutan E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:359)
at java.lang.Integer.parseInt(Integer.java:332)
at id.nijushop.ikutan.ProductDetail$1.onClick(ProductDetail.java:150)
at android.view.View.performClick(View.java:4084)
at android.view.View$PerformClick.run(View.java:16966)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Please, some one fix my code...I think i need to do something about this
quantity.findViewById(R.id.quantityOrder)// need to set to Interger
The problem is in this line:
listData2[i] = Integer.parseInt(quantityOrder.getText().toString()); // set edittext to int
The Integer.parseInt(String string) method will return an int or throw a NumberFormatException if passed string is not a valid integer string. An empty string - "" doesn't make up a valid integer, so if your EditText is empty, the problem arises.
You need to shield the execution of parseInt with a try - catch block catching a NumberFormatException and act accordingly - abort the method or else, but you obviously cannot continue with your arithmetic if you haven't provided a valid number.
Also, the thing that would help you is, within your EditText element in xml file, include an inputType property, for example:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number|numberSigned" />
This inputType property will cause the system to use an automatic inputFilter and provideonly numeric soft keyboard, so the user cannot enter an invalid number (in this case, only a signed integer). However this will still not account for empty input, so you'll need to either catch NumberFormatException or check whether string from your EditText is not empty. (!string.isEmpty())
I built an android app that casts a spinner to a switch, to enable the user to select an operator for a calculation and see the result.
It is from the Android Boot Camp lessons. I was unhappy to find my app had no compile errors but crashed on start-up. I was watching the logcat as I ran the application and found the nullpointer exception to be on line 40. Where I pull the spinner's selection to a string variable.
//spinner
op3 = operation.getSelectedItem().toString();
I dumped the contents of my logcat to a text file. Here is what I think is relevant.
09-30 22:26:58.401: E/AndroidRuntime(1565): FATAL EXCEPTION: main
09-30 22:26:58.401: E/AndroidRuntime(1565): Process: com.schmop.flashmath, PID: 1565
09-30 22:26:58.401: E/AndroidRuntime(1565): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.schmop.flashmath/com.schmop.flashmath.MainActivity}: java.lang.NullPointerException
and
**09-30 22:26:58.401: E/AndroidRuntime(1565): Caused by: java.lang.NullPointerException
09-30 22:26:58.401: E/AndroidRuntime(1565): at** com.schmop.flashmath.MainActivity.onCreate(MainActivity.java:40)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Activity.performCreate(Activity.java:5231)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-30 22:26:58.401: E/AndroidRuntime(1565): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-30 22:26:58.401: E/AndroidRuntime(1565): ... 11 more
Here is the contents of my mainActivity in
MainActivity.java
public class MainActivity extends ActionBarActivity {
int number1;
int number2;
int result;
int op1;
int op2;
String op3 = null;
int calculator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText)findViewById(R.id.num);
final EditText second = (EditText)findViewById(R.id.num2);
final Spinner operation = (Spinner)findViewById(R.id.operator);
final Button equals = (Button)findViewById(R.id.button1);
final TextView t = (TextView)findViewById(R.id.result);
operation.setSelection(0);
//spinner
op3 = operation.getSelectedItem().toString();
//start logic
//onclick listener
equals.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//gettext
number1 = Integer.parseInt(first.getText().toString());
number2 = Integer.parseInt(second.getText().toString());
if(number1 < 21 && number1 > 0 && number2 < 21 && number2 > 0) {
//switch
switch(calculator) {
case 1: op3 = "+";
calculator = number1 + number2;
break;
case 2: op3 = "-";
calculator = number1 - number2;
break;
case 3: op3 = "x";
calculator = number1 * number2;
break;
}
} else {
t.setText("Error: One of your Numbers is out of Range");
}
t.setText(number1 + op3 + number2 + "=" + calculator);
}
});
//end logic
}
Since it was calling a null variable, I tried adding junk data into the declaration of op3 as an attempt to fix my problem. This proved unsuccessful. I've seen some examples being solved by adding a check for null in an if statement, however I dont think it would apply here.
Documentation for getSelectedItem():
Returns The data corresponding to the currently selected item, or null if there is nothing selected.
When the app is starting up, nothing is yet selected. Move the
op3 = operation.getSelectedItem()
inside the onClick() and check for != null before trying to call toString() on the result.
You haven't set any contents for the spinner, so operation.getSelectedItem() is returning null. The NPE is from trying to then call toString(). Populate your spinner first before trying to access items, or at least put a null check when you try to retrieve an item.
I have data inside a table. when I set adapter from it, the app crashes, but if I load the info from server then everything is ok. I get NullPointerException on setting the listview's adapter. even though, I do exactly same things as when table is empty.
// check if database is empty
cursor = sh.getReadableDatabase().rawQuery(
"SELECT * FROM " + PetopenTable.TABLE_NAME, null);
if (cursor.getCount() < 1) {
//cursor is empty
tableHasData = false;
} else {
tableHasData = true;
}
if (tableHasData) {
// we have data in database, show it, then get info
// from server and reload the UI
Log.d("Cursor", "PetOpenFragment; cursor is not empty");
prepareListFromCursor(cursor);
// initialize the list
lview3 = (ListView) getActivity().findViewById(R.id.listView1);
adapter = new ListViewCustomAdapter(getActivity(), itemList);
// here adapter is not null
if (adapter != null) {
Log.d("Adapter in Petopen", "is not null");
lview3.setAdapter(adapter); // line 94
} else {
Log.d("ADapter in petopen", "is null");
}
// do not show the loading message as we can fill it instantly from database
// now get data from server to update
new getPetopenUsers().execute((Void) null);
} else {
// show loading and load from server, database is empty
Log.d("Cursor", "PetOpenFragment; cursor is empty");
new getPetopenUsers().execute((Void) null);
mDialog.setMessage("Loading...");
mDialog.setCancelable(false);
mDialog.show();
}
...
// inside prepareListFromCursor I initialize the itemlist
itemList = new ArrayList<Object>();
...
//when i get data from server, i initialize same as when there is data in table
lview3 = (ListView) getActivity().findViewById(R.id.listView1);
adapter = new ListViewCustomAdapter(getActivity(), itemList);
lview3.setAdapter(adapter);
Logcat error:
ATAL EXCEPTION: main
java.lang.NullPointerException
at com.petcial.petopen.fragments.petOpenFragment.onCreateView(petOpenFragment.java:94)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:440)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:126)
at dalvik.system.NativeStart.main(Native Method)
Update
Here is how i fill the itemList, i call this method after i parse the info from table
private void AddObjectToList(String image, String name, String status,
String distance, String location, String[] petImage,
String[] petName) {
// TODO Auto-generated method stub
bean = new ItemBean();
bean.setProfileImage(image);
bean.setName(name);
bean.setStatus(status);
bean.setDistance(distance);
bean.setLocation(location);
bean.setPetImage(petImage);
bean.setPetName(petName);
itemList.add(bean);
}
Finally I tried putting the whole thing which loads data from database inside an AsyncTask, and it worked. In case someone faced same problem here is how you have to do it:
Create an AsyncTask, which is called from onCreate or onViewCreated(as in my case, I fragment)
In the doInBackground method I did not have anything, instead in the onPostExecute method, i call all the methods that processes all the data from cursor and initializes the list and adapter.
If someone has a better solution on how to make this inside an AsyncTask, please answer to this post.
I have a database with some records in and i have the code i wish to execute on each row but I'm having trouble creating a suitable loop, ive been trying while(movetonext) but it hasnt been working.
cursor = getAppts();
cursor.moveToNext();
String titlefromdb = cursor.getString(3);
if (strTitle.equals(titlefromdb) && cursor.getString(1).equals(dateselforap))
{
// matching code update box
final Dialog matchdiag = new Dialog(CW2Organisor.this);
matchdiag.setContentView(R.layout.apptmatch);
matchdiag.setTitle("View/Edit Appointment");
matchdiag.setCancelable(true);
TextView matchtxt = (TextView) matchdiag.findViewById(R.id.matchtxt);
matchtxt.setText("Appointment \"" + titlefromdb + "\" already exists, please choose a different event title");
Button btnmatchok = (Button) matchdiag.findViewById(R.id.btnmatch);
btnmatchok.setOnClickListener(new OnClickListener() {
// on click for cancel button
#Override
public void onClick(View v) {
matchdiag.dismiss();
}
});
matchdiag.show();
}
else
{
addAppt(strTime, strTitle, strDet);
dialog.dismiss();
}
What I would need is for each row of my database i would need the titlefromdb to hold the title field of the current row and the for the if statement to run and then move to the next row.
You could try
cursor.moveToFirst();
loop with some sort of check
cursor.moveToNext();
end loop
... and I would also try to qualify your "it's not working" statement. What's not working?