I am creating a function for an app where the user supplies some items and the app then the app gets prices from a database. These prices are put in a map , and after async task is complete , the permutation function starts. What it IS meant to do id to go through all permutations based on combinations which change based on input from the user.I am getting ava.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object referenceMy code is as follows:
latest.java
public class latest extends AppCompatActivity {
String major = "";
TextView textView;
public static Map<String,Map<String,Integer>> cart_names = new HashMap<>();
public static Map<String,Map<String,Integer>> cart_names2 = new HashMap<>();
ProgressDialog pd;
ArrayList<String> strhold = new ArrayList<String>();
Activity context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_latest);
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
textView = (TextView) findViewById(R.id.main_text);
context=this;
for (int s=0;s<Search_multiple.cart_records.size();s++){
strhold.add(Search_multiple.cart_records.get(s).getName());
}
if (strhold.size()>0) {
BackTask backTask = new BackTask();
backTask.execute(strhold);
}
}
#Override
public void onStart(){
super.onStart();
String arr[]={};
}
public void goto_main_confirm(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
/* public static void setCart_records(Items item){
cart_records.add(item);
}*/
public void goto_cart_confirm(View view) {
Intent someintent = new Intent(this, CartActiviy.class);
startActivity(someintent);
}
private class BackTask extends AsyncTask<ArrayList<String>, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd.setTitle("Retrieving data");
pd.setMessage("Please wait.");
pd.setCancelable(true);
pd.setIndeterminate(true);
pd.show();
}
protected Void doInBackground(ArrayList<String>... arg0) {
InputStream is = null;
String result = "";
try {
ArrayList<String> name = arg0[0];
String link = "http://chutte.co.nf/get_item_prices.php?";
for (int b = 0; b < name.size(); b++) {
link += "names[]" + "=" + name.get(b);
if (b != name.size() - 1) {
link += "&";
}
}
Log.e("ERROR", link);
URL url = new URL(link);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
is = urlConnection.getInputStream();
} catch (Exception e) {
if (pd != null)
pd.dismiss();
Log.e("ERROR", e.getMessage());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line + "\n");
}
is.close();
result = builder.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
try {
result = result.substring(result.indexOf("["));
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Map<String, Integer> temmap = new HashMap<>();
String temname = jsonObject.getString("Name");
temmap.put("First", jsonObject.getInt("First"));
strhold.add("First");
temmap.put("Second", jsonObject.getInt("Second"));
strhold.add("Second");
temmap.put("Third", jsonObject.getInt("Third"));
strhold.add("Third");
Log.e("ERROR", temmap.get("First").toString());
cart_names.put(temname, temmap);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss();
Log.e("size", cart_names.size() + " ");
if (cart_names.size() == 0) {
textView.setText("Sorry, Error applying data \n" + "Please contact customer service........");
} else {
String[] strhold1 = new String[strhold.size()];
for (int i = 0; i < strhold.size(); i++) {
strhold1[i] = strhold.get(i);
}
Combination.printCombination(strhold1, strhold.size(), 2);
}
}
}
}
Combination.java
Public class Combination {
/* arr[] ---> Input Array
data[] ---> Temporary array to store current combination
start & end ---> Staring and Ending indexes in arr[]
index ---> Current index in data[]
r ---> Size of a combination to be printed */
public static ArrayList<String> finalmap = new ArrayList<>();
public static void combinationUtil(String arr[], String data[], int start,
int end, int index, int r)
{
// Current combination is ready to be printed, print it
if (index == r)
{
ArrayList<String> stringArrayList = new ArrayList<String>();
for (int j=0; j<r; j++)
stringArrayList.add(data[j]);
permute(stringArrayList,0);
return;
}
// replace index with all possible elements. The condition
// "end-i+1 >= r-index" makes sure that including one element
// at index will make a combination with remaining elements
// at remaining positions
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r);
}
}
// The main function that prints all combinations of size r
// in arr[] of size n. This function mainly uses combinationUtil()
public static void printCombination(String arr[], int n, int r)
{
// A temporary array to store all combination one by one
String data[]=new String[r];
for(int no = 0;no<arr.length;no++){
boolean decider = true;
for (Map.Entry<String,Map<String,Integer>> entry : latest.cart_names.entrySet()){
if(latest.cart_names.get(entry.getKey()).get(arr[no])==0){
decider=false;
}
}
if (finalmap.size()==0) {
if (decider) {
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr[no]);
}
}
}else{
if (decider) {
int sum1 = 0;
int sum2 = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2 += latest.cart_names.get(entry.getKey()).get(arr[no]);
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr[no]);
}
}
}
}
}
// Print all combination using temprary array 'data[]'
combinationUtil(arr, data, 0, n-1, 0, r);
}
public static void permute(ArrayList<String> arr, int k){
for(int i = k; i < arr.size(); i++){
java.util.Collections.swap(arr, i, k);
/*int sum1 = 0;
int sum2 = 0;
int man = 0;
for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2+=latest.cart_names.get(entry.getKey()).get(arr.get(man));
man++;
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr.get(rt));
}
}*/
permute(arr, k+1);
java.util.Collections.swap(arr, k, i);
/* for (Map.Entry<String, Map<String, Integer>> entry : latest.cart_names.entrySet()) {
sum1 += latest.cart_names.get(entry.getKey()).get(finalmap);
sum2+=latest.cart_names.get(entry.getKey()).get(arr.get(man));
man++;
}
if (sum2>sum1){
for (int rt = 0; rt < latest.cart_names.size(); rt++) {
finalmap.add(arr.get(rt));
}
}
}
if (k == arr.size() -1){
for(int woman = 0;woman<finalmap.size();woman++) {
System.out.println(finalmap.get(woman));
}*/
}
}
}
Log
6-15 15:06:41.850 3538-3538/nf.co.riaah.chutte D/AndroidRuntime: Shutting down VM
--------- beginning of crash
06-15 15:06:41.850 3538-3538/nf.co.riaah.chutte E/AndroidRuntime: FATAL EXCEPTION: main
Process: nf.co.riaah.chutte, PID: 3538
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
at nf.co.riaah.chutte.Combination.printCombination(Combination.java:54)
at nf.co.riaah.chutte.latest$BackTask.onPostExecute(latest.java:173)
at nf.co.riaah.chutte.latest$BackTask.onPostExecute(latest.java:83)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:139)
at android.app.ActivityThread.main(ActivityThread.java:5298)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
06-15 15:06:41.851 3538-3538/nf.co.riaah.chutte D/AppTracker: App Event: crash
06-15 15:06:41.883 3538-3538/nf.co.riaah.chutte I/Process: Sending signal. PID: 3538 SIG: 9
06-15 15:06:43.255 3918-3918/nf.co.riaah.chutte D/ThreadedRenderer: mThreadGroupCpuId 2 mRenderThreadCpuId 2 affinity
Have a look at Combination.java line 54 wich seams to be if(latest.cart_names.get(entry.getKey()).get(arr[no])==0) (If I counted correctly) so the Integer in the Map seams to be null. I recommend so add some log-output or to debug to find out which entry exactly is the problem and than check if you need to add a bull-check or fix your data.
Maybe arr[no] is null.
I recommend to split the line and make some log-outputs to find the problem (or use a debugger)
To find the cause of the problem I would replace:
if(latest.cart_names.get(entry.getKey()).get(arr[no])==0)
to
System.err.println("no: "+no);
String arrayElement=arr[no];
System.err.println("arrayElement: "+arrayElement);
Map<String,Integer> outerMapValue = entry.getValue();
System.err.println("outerMapValue: "+outerMapValue);
if(outerMapValue.get(arrayElement)==0)
Remarks:
if(latest.cart_names.get(entry.getKey()) can be replaced with entry.getValue()
Map<String,Map<String,Integer>> Is not very easy to understand while reading the code. You may consider to introduce a type to wrap the inner Map<String,Integer>
Related
I have an arraylist in which I have ESSID, BSSID, Strenght of access Point on first three indexes, and from Index 4 to 6 I have again ESSID, BSSID, Strength of another AccessPoint. I want to store this list in database like first three values save in one row of table. and next three values save in 2nd row of table.
String[] namesArr = new String[arrayList2.size()]; //conver arraylist to array
for (int j = 0; j < arrayList2.size(); j++){
namesArr[j] = arrayList2.get(j);
int length = namesArr[j].length();
for (int k = 0; k < length; k += 3) {
ssid = namesArr[k];
bssid = namesArr[k + 1];
rssid = namesArr[k + 2];
}
insertValues(this);
}
public void insertValues(View.OnClickListener view){
SendData send = new SendData(this);
send.execute(bssid,ssid,rssid);}
I have made a class to store this data in database that works fine.
public class SendData extends AsyncTask<String, Void, String> {
AlertDialog dialog;
Context context;
public SendData(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message");
}
#Override
protected void onPostExecute(String s) {
dialog.setMessage(s);
dialog.show();
}
#Override
protected String doInBackground(String... voids) {
String data = "";
String result = "";
String MAC = voids[0];
String Name = voids[1];
String Strength = voids[2];
String con_Str = "http://10.5.48.129/Webapi/accesspoints_data/create.php";
try{
URL url = new URL(con_Str);
HttpURLConnection http = (HttpURLConnection) url.openConnection();
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);
OutputStream out_Stream = http.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out_Stream, "UTF-8"));
JSONObject obj = new JSONObject();
try {
obj.put("BSSID", MAC);
obj.put("ESSID", Name);
obj.put("RSSID", Strength);
} catch (JSONException e) {
e.printStackTrace();
}
data = obj.toString();
writer.write(data);
writer.flush();
writer.close();
out_Stream.close();
InputStream in_Stream = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in_Stream, "ISO-8859-1"));
String line = "";
while ((line = reader.readLine()) != null)
{
result += line;
}
reader.close();
in_Stream.close();
http.disconnect();
return result;
} catch (MalformedURLException e){
result = e.getMessage();
} catch (IOException e){
result = e.getMessage();
}
return result;
}
}
SendData class is perfectly working but problem is with for loop.
I think this is result that you are expecting :
List<String> arrayList2 = new ArrayList<>();
arrayList2.add("1");
arrayList2.add("2");
arrayList2.add("3");
arrayList2.add("4");
arrayList2.add("5");
arrayList2.add("6");
arrayList2.add("6");
arrayList2.add("7");
arrayList2.add("8");
arrayList2.add("9");
arrayList2.add("10");
List<String[]> sarrayList = new ArrayList<>();
String[] arr = new String[3];
int i = 0;
for (int j = 0; j < arrayList2.size(); j++)
{
arr[i] = arrayList2.get(j);
i++;
if((j+1)%3==0)
{
sarrayList.add(arr);
i = 0;
arr = new String[3];
}
}
for(String [] sa:sarrayList)
{
for(String s:sa)
{
System.out.println(s);
}
System.out.println("=========");
}
This might not be the most efficient way of doing it. But it splits the ArrayList in to String arrays of length=3 and stores them in a new ArrayList named sarrayList
I would advise to use a datastructure to hold the record. See the code below this is a small example how you could do it
ArrayList<Record> records;
for (int i = 2; i < inputArrayList.size(); i = i + 3){
string ssid = namesArr.get(i - 2);
string bssid = namesArr.get(i - 1);
string rssid = namesArr.get(i);
records.add(new Record(ssid, bssid, rssid));
}
class Record{
string ssid;
string bssid;
string rssid;
// Constructor...
// Getter and setter to be implemented...
}
ok from what i understand you want to divide the arraylist each 3 elements thats how you do it with streams and it will return an a collection of arraylists each one has 3 elements
final int chunkSize = 3;
final AtomicInteger counter = new AtomicInteger();
//arrayList here us your array list
final Collection<List<String>> result = arrayList.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / chunkSize))
.values();
and mentioning supermar10 answer you code make a class to map the strings to it like that
class Record{
string ssid;
string bssid;
string rssid;
Record(String ssid,String bssid,String rssid){
this.ssid=ssid;
this.bssid=bssid;
this.rssid=rssid;
}
}
now you have a class to map to now save the records in a list of Record
create a a list in the main class
static List<Record> lists=new ArrayList<>();
then map the data like that
result.stream().forEach(nowList -> saveRecord(nowList));
and thats the save method
static void saveRecord(List<String> list){
lists.add(new Record(list.get(0),list.get(1),list.get(2)));
}
I have simplified it to one loop and also modified insertValues so that it takes 3 more parameters. This
int size = arrayList2.size();
for (int j = 0; j < size; j += 3) {
if (size - j < 3 ) {
break;
}
String ssid = arrayList2.get(j);
String bssid = arrayList2.get(j + 1);
String rssid = arrayList2.get(j + 2);
insertValues(this, ssid, bssid, rssid);
}
if one the other hand ssid and so on are class variables the inside of the loop can be changed to
ssid = arrayList2.get(j);
bssid = arrayList2.get(j + 1);
rssid = arrayList2.get(j + 2);
insertValues();
im using android studio for a school project and im in the final stages now. the only thing i have left is for one class that has 2 spinners, one determining the program, and the other determining the semester, and a button that will then take those two spinners and spit out a URL pertaining to the schedule of that program and semester. The problem is, i dont know how to then take that spit out URL, and parse it into the other java class that displays a schedule. Below you will find the code attached, that works but doesnt display the correct schedule(since its hardcoded)
StringBuffer sb = new StringBuffer();
sb.append("http://branko-cirovic.appspot.com/etcapp/timetables/timetable_"); sb.append(cid); sb.append(semester); sb.append(".xml");
loc = sb.toString();
Toast.makeText(ScheduleMainActivity.this,"You Selected : "
+ loc, Toast.LENGTH_SHORT).show();
Intent toy7 = new Intent(ScheduleMainActivity.this, TimetableMainActivity.class);
toy7.putExtra("Name", loc);
startActivity(toy7);
That is the activity where im creating the intent and using the putExtra to use the data in the next activity
public class GetXML extends AsyncTask<String, Void, String> {
String src = null;
String loc = (String) getIntent().getExtras().get("Name");
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL(loc);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
src = readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
return src;
}
#Override
protected void onPostExecute(String result) {
if (src == null)
new AlertDialog.Builder(TimetableMainActivity.this).
setTitle("Error").setMessage("No Schedule Found").
setNeutralButton("Close", null).show();
else {
parseXML(src);
}
setContentView(R.layout.activity_main_timetable);
days = new String[5][10];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 10; j++) {
int k = i * 10 + j;
days[i][j] = schedule.get(k);
}
}
for (int i = 0; i < 5; i++)
list[i] = new ArrayList<Map<String, String>>();
int count = hours.length;
for (int j = 0; j < 5; j++) {
for (int i = 0; i < count; i++) {
map = new HashMap<String, String>();
map.put("time", hours[i]);
map.put("description", days[j][i]);
list[j].add(map);
}
}
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_WEEK) - 2;
pos = 0;
if (today >= 0 && today <= 4)
pos = today;
ViewPager viewPager = findViewById(R.id.ViewPager);
CustomPagerAdapter adapter = new CustomPagerAdapter(TimetableMainActivity.this, list);
PagerTabStrip pagerTabStrip = findViewById(R.id.pager_tab);
int color = Color.parseColor("#33b7ee");
pagerTabStrip.setTabIndicatorColor(color);
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(pos);
}
This is where im getting an error. Im getting an IndexOut of bounds error and the app is crashing
2018-11-20 22:35:19.126 20681-20681/com.example.mr_ru.listview E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mr_ru.listview, PID: 20681
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.mr_ru.listview.TimetableMainActivity$GetXML.onPostExecute(TimetableMainActivity.java:100)
at com.example.mr_ru.listview.TimetableMainActivity$GetXML.onPostExecute(TimetableMainActivity.java:66)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
This is the error btw
I am working on a driving licence project on j2Me wich is including Tests like quizz , well and i am having a problem after parsing the questions and moving them into choiceGroups just like that :
if (questions.length > 0) {
for (int i = 0; i < questions.length; i++) {
ChoiceGroup reponses = new ChoiceGroup("Reponses" + i, Choice.EXCLUSIVE);
reponses.append(questions[i].getReponse1(), null);
reponses.append(questions[i].getReponse2(), null);
reponses.append(questions[i].getReponse3(), null);
pass.append(questions[i].getContenu());
pass.append(reponses);
}
}
} catch (Exception e) {
System.out.println("Exception:" + e.toString());
}
disp.setCurrent(pass);
and the next step is the command who's controlling the choiceGroups to test them if they are like the true answer or not .
so i am blocked here .
if (c == valider) {
int result = 0;
for (int i = 0; i < pass.size(); i++) {
String ch = pass.get(i).getLabel();
System.out.println(ch);
}
}
I don't know how to get the choice from the choicegroup
any help
Actually, I am not sure what totally you want for:
This code will help you get selected items from choicegroup that i did long time before:
//get a selected array in choicegroup
private String[] choiceGroupSelected(ChoiceGroup cg) {
String selectedArray[] = new String[cg.size()];
int k = 0;
for (int i = 0; i < cg.size(); i++) {
if (cg.isSelected(i)) {
selectedArray[k] = cg.getString(i);
k++;
}
}
return selectedArray;
}
That function will help me get all selected items for deleting action below:
private void deleteSpecificItem() {
try {
String temp = null;
int index;
//get ChoiceGroup size
int numbers = cgTrip.size();
String selectedItems[] = choiceGroupSelected(cgTrip);
//
rs = services.RecordStoreManager.openRecordStoreByName("TripRS");
re = rs.enumerateRecords(null, null, true);
String[] tripList = new String[2];
for (int i = 0; i < numbers; i++) {
temp = selectedItems[i];
if (temp != null) {
while (re.hasNextElement()) {
try {
index = re.nextRecordId();
System.out.println("RecordID: " + index);
byte[] byteBuff = rs.getRecord(index);
String source = new String(byteBuff);
tripList = services.StringManager.getItems(source, ";", 2);
String strProcess = tripList[0] + "-" + tripList[1];
//inspect all of items in choicegroup and if they are selecting then compare with record
//If comparison is true then delete this record
if (temp.equals(strProcess)) {
System.out.println("Delete RecordID: " + index);
rs.deleteRecord(index);
re.keepUpdated(true);
break;
}
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
}
}
}
try {
rs.closeRecordStore();
} catch (RecordStoreException ex) {
ex.printStackTrace();
}
rs = null;
re.destroy();
this.LoadTripItem();
} catch (RecordStoreNotOpenException ex) {
ex.printStackTrace();
}
}
In this code I want to search in an ArrayList but my code returns an incorrect result and I can not resolve this problem.
ReceivedItemStructure structure:
public class ReceivedItemStructure {
public String mLastID;
public String mUserID;
public String mSmsBody;
public String mMobileNumber;
public String mDate;
public String mSenderName;
public String mSmsNumber;
public String mContactName;
public String getmLastID() {
return mLastID;
}
}
My Code:
int countSMS = 0;
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
for (ReceivedItemStructure rf:items){
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
}
}
}
My problem is this line :
if( ! mId.equals(rf.getmLastID()) ) {
if mId = 2000 and rf.getmLastID() = 1000 then count must be ++
Loop through your list and do a contains or startswith.
ArrayList<String> resList = new ArrayList<String>();
String searchString = "man";
for (String curVal : list){
if (curVal.contains(searchString)){
resList.add(curVal);
}
}
You can wrap that in a method. The contains checks if its in the list. You could also go for startswith.
Ok so to clarify please try to debug your code like this:
int countSMS = 0;
String TAG = "Debugger";
String smsReceivedSender = "";
String r = new JsonService(config_username, config_password, 0, 20, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
Log.i(TAG, "items size is " + items.size());
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mId = json_obj.getString("id_recived_sms");
Log.i(TAG, "Trying to compare " + mId);
for (ReceivedItemStructure rf:items){
Log.i(TAG, "iteration step of " + rf.getmLastID);
if( ! mId.equals(rf.getmLastID()) ) {
countSMS++;
Log.i(TAG, "they are equal, count is " + countSMS);
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class database {
String fileName;
Scanner input;
String[][] data;
List<String> useful_list;
List<String> records;
ArrayList<Object> handles;
public database(String fileName) {
this.fileName = fileName;
}
public void openFile() {
try {
input = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
}
}
public void readRecords() {
// Read all lines (records) from the file into an ArrayList
records = new ArrayList<String>();
try {
while (input.hasNext())
records.add(input.nextLine());
} catch (Exception e) {
// TODO: handle exception
}
}
public void parseFields() {
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = records.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row = 0;
for (String record : records) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row] = new String[cols]; // create columns for current row
int col = 0;
while (tokens.hasMoreTokens()) {
data[row][col] = tokens.nextToken().trim();
col++;
}
row++;
}
}
public static void main(String[] args) {
String filename = null;
String[] values = new String[4];
String input = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
filename = reader.readLine();
input = reader.readLine();
values = input.split(",");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
int[] input1;
input1 = new int[4];
try {
for (int j = 0; j < values.length; j++) {
input1[j] = Integer.parseInt(values[j]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
if (input1[0] >= 4 || input1[0] <= 0) {
System.out.println("Invalid Input");
return;
}
database file1 = new database(filename);
file1.openFile();
file1.readRecords();
file1.parseFields();
file1.search(input1[1]);
if (file1.useful_list.size() == 0) {
System.out.println("Data Unavailable");
return;
}
file1.sortarray(input1[0] - 1);
int width = input1[2];
int skip = (input1[3] - 1) * width;
Iterator<Object> it = file1.handles.iterator();
for (int i = 1; i <= skip; i++) {
if (it.hasNext()) {
it.next();
} else {
System.out.println("Data Unavailable");
return;
}
}
for (int j = 1; j <= width && it.hasNext(); j++) {
String[] a = (String[]) it.next();
for (int i = 0; i < a.length; i++)
if(i<a.length-1)
System.out.print(a[i] + ",");
else
System.out.print(a[i]);
System.out.println();
}
}
void sortarray(final int index) {
handles = new ArrayList<Object>();
for (int i = 0; i < data.length; i++)
handles.add(data[i]);
Collections.sort(handles, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
String[] a = (String[]) o1;
String[] b = (String[]) o2;
if (index == 1 || index == 0) {
int left = Integer.parseInt(a[index]);
int right = Integer.parseInt(b[index]);
return Integer.compare(left, right); //Line 165
} else {
if (a.length == 0 && b.length == 0)
return 0;
if (a.length == 0 && b.length != 0)
return 1;
if (a.length != 0 && b.length == 0)
return -1;
return a[index].compareTo(b[index]);
}
}
public boolean equals(Object o) {
return this == o;
}
});
}
void search(int searchs) {
useful_list = new ArrayList<String>();
for (int row = 0; row < data.length; row++) {
if (Integer.parseInt(data[row][0]) == searchs) {
// store in array list
useful_list.add(data[row][0] + "," + data[row][1] + ","
+ data[row][2] + "," + data[row][3]);
}
}
if (useful_list.size() == 0) {
return;
}
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = useful_list.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row1 = 0;
for (String record : useful_list) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row1] = new String[cols]; // create columns for current row
int col1 = 0;
while (tokens.hasMoreTokens()) {
data[row1][col1] = tokens.nextToken().trim();
col1++;
}
row1++;
}
}
}
this code is working fine on eclipse .
but if i submit it for my online compilation ..
it shows compile time error.
error message
*database.java 163 cannotfindsymbolsymbol methodcompare int int location class java.lang.Integer return Integer.compare left right ;^1error*
Integer.compare was introduced to Java in version 1.7. Chances are that the online compiler has an earlier version of the compiler
Integer.compare(int,int) was introduced in Java 1.7. I expect you are seeing that error because Java 6 or earlier is used to compile the code. The docs. themselves (linked above) show how to do it for earlier Java (you should consult them at times like this).
Integer.valueOf(x).compareTo(Integer.valueOf(y))