I have an int variable with 6 elements. All the time in the code android sets it to null. I even redefined it in the code in debug mode like this
if (yeahsort == null) {
SharedPreferences prefs2 = getSharedPreferences("KARANTÄN", MODE_PRIVATE);
String savedString = prefs2.getString("string", null);
StringTokenizer st = new StringTokenizer(savedString, ",");
int[] yeahsort = new int[6];
for (int i = 0; i < 6; i++) {
yeahsort[i] = Integer.parseInt(st.nextToken());
}
}
during the for loop the variable yeahsort becomes an int[], but right after it becomes null again. Seriously right after the for loop.
So what can I do to fix this?
Instead of int[] yeahsort = new int[6] change it to yeashsort = new int[6] here is a lesson on variable scoping http://www.java-made-easy.com/variable-scope.html
Related
hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.
I am using realm for Android. I have the following code and it works but I was wondering if it is the best way to go about updating objects and if it would cause any performance issues.
Currently, I do not want to update an existing object if the status is set to processing.
List<WorkOrderObject> woList = new ArrayList<>();
for (int i = 0; i < openWorkOrders.size(); i++) {
if (!visnetawrap.isUserLoggedIn) {
return;
}
WorkOrderObject wo = visnetawrap.gsonClient.fromJson(openWorkOrders.get(i).toString(), WorkOrderObject.class);
WorkOrderObject currWO = realmThread.where(WorkOrderObject.class).equalTo("id", wo.getOrderRawId()).findFirst();
if (currWO != null) {
if (currWO.getOrderStatus().equals("Processing")) {
continue;
}
}
issueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderIssueDate());
issueDateString = issueDateTime.toLocalDateTime().toString("MM/dd/yyyy", Locale.US);
dueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderDueDate());
dueDateString = dueDateTime.toLocalDateTime().toString("MM/dd/yyyy", Locale.US);
if (!issueDateString.equals("") && !issueDateString.equals("00/00/0000") && issueDateTime.getYear() >= now.getYear() && !dueDateString.equals("") && !dueDateString.equals("00/00/0000") && dueDateTime.getYear() >= now.getYear()) {
//Log.d("dueDate", dueDateString);
woList.add(wo);
}
}
realmThread.beginTransaction();
realmThread.copyToRealmOrUpdate(woList);
realmThread.commitTransaction();
I think basically it is the same.
Since you are worried about performance here are ways you can improve.
private static String PROCESSING = "Processing";
private static String DATE_FORMAT = "MM/dd/yyyy";
private static String EMPTY_DATE = "00/00/0000";
public void betterMethod() {
List<WorkOrderObject> woList = new ArrayList<>(openWorkOrders.size());
//I think this code doesnot need to be inside loop.
if (!visnetawrap.isUserLoggedIn) {
return;
}
for (int i = 0, j = openWorkOrders.size(); i < j; i++) {
//Since you are using gson there are ways to convert JsonArray to list directly which is a better way than this
WorkOrderObject wo = visnetawrap.gsonClient.fromJson(openWorkOrders.get(i).toString(), WorkOrderObject.class);
WorkOrderObject currWO = realmThread.where(WorkOrderObject.class).equalTo("id", wo.getOrderRawId()).findFirst();
if (currWO != null && currWO.getOrderStatus().equals(PROCESSING)) { //Its cleanar way
continue;
}
issueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderIssueDate());
issueDateString = issueDateTime.toLocalDateTime().toString(DATE_FORMAT, Locale.US);
dueDateTime = AppUtils.formatTimestampToDateTime(wo.getOrderDueDate());
dueDateString = dueDateTime.toLocalDateTime().toString(DATE_FORMAT, Locale.US);
//I assume you have stripped out code where it needs string
//You can use TextUtils.isEmpty() or issueDateString.isEmpty() ,
// issueDateString.equals("") does is creates new String which is empty and compares issueDateString with it while above methods just check the
//length of string
if (!TextUtils.isEmpty(issueDateString) && !issueDateString.equals(EMPTY_DATE) && issueDateTime.getYear() >= now.getYear() && !TextUtils.isEmpty(dueDateString) && !dueDateString.equals(EMPTY_DATE) && dueDateTime.getYear() >= now.getYear()) {
//Log.d("dueDate", dueDateString);
woList.add(wo);
}
}
if (!woList.isEmpty()) {
realmThread.beginTransaction();
realmThread.copyToRealmOrUpdate(woList);
realmThread.commitTransaction();
}
}
For loop can be very large so conditional statement like currWO.getOrderStatus().equals("Processing") will create an new string and compares. It's better to initialize the string before and pass as above.
Converting JsonArray to List
Why instantiating arrays like new ArrayList<>(openWorkOrders.size()) and using for loop with list like for (int i = 0, j = openWorkOrders.size(); i < j; i++) {}
Streamlining Android Apps: Eliminating Code Overhead by Jake Wharton
i am trying enter link description here
as to add values to single as well as 2dim array dynamically,
but while adding values it shows null pointer ,
here is my code
Arr points1[];
points1 = new Arr[listItemList.size()];
for(int i=0;i<listItemList.size();i++)
{
ListItemReminderSummary listItem = listItemList.get(i);
Log.i("listItem.Car_Id", listItem.Car_Type);
points1[i].Car_Id = listItem.Car_Id;
points1[i].Car_Type = listItem.Car_Type;
}
for(int i=0;i<listItemList.size();i++)
{
System.out.println( points1[i].Car_Id + points1[i].Car_Type);
}
Null pointer at points1[i].Car_Id = listItem.Car_Id;
any suggestion,
thnx in advance.
initialize the items in Array...
for (int i = 0; i < listItemList.size(); i++) {
ListItemReminderSummary listItem = listItemList.get(i);
Log.i("listItem.Car_Id", listItem.Car_Type);
points[i] = new Arr();
points1[i].Car_Id = listItem.Car_Id;
points1[i].Car_Type = listItem.Car_Type;
}
You have to initialize cells of array.
for(int i=0;i<listItemList.size();i++){
points[i] = new Arr();
}
You have not Allocated memory to the Arr that is why you're trying to dereference an uninitialised pointer (i.e. writing to a random chunk of memory), which is undefined behaviour.
Change ur starting 2 lines
Arr points1[] = new Arr[listItemList.size()];
for (int i = 0; i < listItemList.size(); i++)
{
ListItemReminderSummary listItem = listItemList.get(i);
Log.i("listItem.Car_Id", listItem.Car_Type);
points1[i].Car_Id = listItem.Car_Id;
points1[i].Car_Type = listItem.Car_Type;
}
Did you make sure that listItemList.get(i) returns a value? Perhaps there is nothing returned from this.
I am trying to take my 4 String arrays and convert them in to a single string separated by a ",". It seems to save the information easy enough when I debug; however, when I try and getString - it doesn't retrieve the data. I'm trying to determine why:
String[] debtName = new String[10];
String[] debtAmount = new String[10];
String[] debtRate = new String[10];
String[] debtPayment = new String[10];
//Load Data
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = sharedPref.getString("debtNames", null).split(",");
//End Load
Bundle extras = getIntent().getExtras();
int flipper = 0;
for(int i=0;i<debtName.length;i++)
{
if(debtName[i].equals(null) && !extras.equals(null) && flipper!=1)
{
debtName[i] = extras.getString("newDebtName");
debtAmount[i] = extras.getString("newDebtAmount");
debtRate[i] = extras.getString("newDebtRate");
debtPayment[i] = extras.getString("newDebtPayment");
flipper = 1;
}
}
..............
StringBuilder value = new StringBuilder("");
SharedPreferences.Editor editor= sharedPref.edit();
for (String i : debtName) {
value.append(i + ",");
}
editor.putString("debtNames", value.toString());
for (String i : debtAmount) {
value.append(i + ",");
}
editor.putString("debtAmounts", value.toString());
for (String i : debtRate) {
value.append(i + ",");
}
editor.putString("debtRates", value.toString());
for (String i : debtPayment) {
value.append(i + ",");
}
editor.putString("debtPayments", value.toString());
editor.commit();
Correction, when run outside of debug, this gives a nullpointer exception on:
SharedPreferences sharedPref= getSharedPreferences("chaosdatasnowball", 0);
debtName = sharedPref.getString("debtNames", null).split(","); <---this line
Here is where the activity is called:
EditText editDebtName = (EditText) findViewById(R.id.dispDebtName);
debtName = editDebtName.getText().toString();
EditText editDebtAmount = (EditText) findViewById(R.id.dispDebtAmount);
String debtAmountStr = editDebtAmount.getText().toString();
EditText editDebtRate = (EditText) findViewById(R.id.dispDebtRate);
String debtRateStr = editDebtRate.getText().toString();
EditText editDebtPayment = (EditText) findViewById(R.id.dispDebtPayment);
String debtPaymentStr = editDebtPayment.getText().toString();
Intent i = new Intent(this, DebtList.class);
i.putExtra("newDebtName", debtName);
i.putExtra("newDebtAmount", debtAmountStr);
i.putExtra("newDebtRate", debtRateStr);
i.putExtra("newDebtPayment", debtPaymentStr);
startActivity(i);
The problem is with this line:
debtName = sharedPref.getString("debtNames", null).split(",");
It is possible that the key debtNames does not exist. Therefor null is returned.
This will happen when you run the app for the first time and have not saved anything to the shared preference yet.
Add a check for null and handle this case. Something like, if null is returned, then show default values, else show values that are read from sharedpreference.
I have surrendered to the apparent fact that there is no valid way to do this so I have hard coded 40 variables in to the app now. If anyone comes up with anything useful, please feel free to post it and I'll check this every so often.
I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.