If I run above and below code in separate projects, it works. But when I try integrate them, the graph is not getting populated.
The reason I feel is in postExecute method because
One important thing to notice is when I run any other random project, make some change in it, and relaunch the app then for some moments Graph.java is visible as it is in background. At that moment, output is coming perfectly.
But if I run the Graph.java , it's showing blank graph.
EDIT
{{ 1st code is to fetch data from URL and store it in various arrays.
2nd code is to diaplay data on graph.
In below code the two arrays passed to graph contain static values, they should take the values from the 1st code. }}
PLEASE HELP
Graph.java
public class Graph extends Activity {
String arr[], arr1[], temp[], company[], current[], close[], time[];
int sub;
String s1;
String[] verlabels = new String[] { " y1 ", " y2 ", " y3 " };
String[] horlabels = new String[] { " x1 ", " x2 ", " x3 ", " x4 " };
private XYPlot mySimpleXYPlot;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://abc.com/stockcharts.aspx?id=Reliance" });
}
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
sub = result.lastIndexOf('#', result.length());
s1 = result.substring(0, sub + 2);
arr1 = s1.split("#");
arr = new String[arr1.length - 1];
company = new String[arr.length];
current = new String[arr.length];
close = new String[arr.length];
time = new String[arr.length];
for (int j = 0; j < arr.length; j++) {
arr[j] = arr1[j];
}
for (int i = 0; i < arr.length; i++) {
temp = arr[i].split(";");
company[i] = temp[0];
current[i] = temp[1];
close[i] = temp[2];
time[i] = temp[3];
}
.
mySimpleXYPlot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
Number[] series1Numbers = { 1324266358000L, 1324266418000L,
1324266478000L, 1324266538000L, 1324266598000L,
1324266658000L, 1324266718000L, 1324266778000L,
1324266838000L, 1324266898000L, 1324266958000L };
Number[] series2Numbers = { 3, 1, 2, 9, 6, 5, 4, 3, 7, 3, 2 };
XYSeries series1 = new SimpleXYSeries(
Arrays.asList(series1Numbers),
Arrays.asList(series2Numbers),
"Company");
LineAndPointFormatter series1Format = new LineAndPointFormatter(
Color.rgb(0, 200, 0), // line color
Color.rgb(0, 100, 0), // point color
Color.rgb(150, 190, 150)); // fill color (optional)
mySimpleXYPlot.addSeries(series1, series1Format);
mySimpleXYPlot.setTicksPerRangeLabel(2);
mySimpleXYPlot.setRangeStep(XYStepMode.INCREMENT_BY_VAL, 1);
mySimpleXYPlot.setDomainValueFormat(new MyDateFormat());
mySimpleXYPlot.disableAllMarkup();
}
public class MyDateFormat extends Format {
private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
#Override
public StringBuffer format(Object obj, StringBuffer toAppendTo,
FieldPosition pos) {
long timestamp = ((Number) obj).longValue();
Date date = new Date(timestamp);
return dateFormat.format(date, toAppendTo, pos);
}
#Override
public Object parseObject(String source, ParsePosition pos) {
return null;
}
}
}
}
I created another class for plotting graph.
Call that class from current class by using intent. Passed the two arrays to graph class by using intent property. plotted the graph in 2nd activity using two arrays.
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();
This is my code which I am using but when I am trying to print dataArray object, then data is not show in JTable. Which model properties of table to print Object array values can used and how?
public class ShowAddressForm extends javax.swing.JFrame {
Object data[][];
Object dataArray[][];
int count = 0;
String st;
public ShowAddressForm(String fname , String str) {
super(fname);
st = str;
initComponents();
fillTable();
}
public void fillTable()
{
int count = 0;
String str;
try
{
BufferedReader br = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = br.readLine()) != null)
{
count++;
}
br.close();
} catch (Exception e)
{
}
Object id;
Object name;
data = new Object[count][7];
int i = 0 , j = 0 , m;
try
{
BufferedReader buffrea = new BufferedReader(new FileReader("D:\\JavaPrograms\\Contact Management System\\InputFiles\\AddressFile"));
while((str = buffrea.readLine()) != null)
{
StringTokenizer token = new StringTokenizer(str , "*");
int n = token.countTokens();
id = token.nextElement();
name = token.nextElement();
String strNameLow = name.toString().toLowerCase();
String strNameUpp = name.toString().toUpperCase();
if(strNameLow.startsWith(st.toLowerCase()) || strNameUpp.startsWith(st.toUpperCase()))
{
data[i][0] = id;
data[i][1] = name;
for(j = 2 ; j < n ; j++)
{
data[i][j] = token.nextElement();
}
i = i + 1;
}
}
buffrea.close();
} catch(IOException ioe){
System.out.println("Error : " + ioe.toString());
}
dataArray = new Object[i][7];
for(int a = 0 ; a < i ; a++)
{
for(int b = 0 ; b < 7 ; b++)
{
dataArray[a][b] = data[a][b];
}
}
//Here is the code to print dataArray object which i used but it is not working, when i am run my program it is print "[Ljava.lang.Object;#1cc2e30" in table's first cell[0][0] position
DefaultTableModel model = (DefaultTableModel)this.data_table.getModel();
model.addRow(dataArray);
}
I filled data in a JTable like this. You might want to give it a try adapting it to your code. Variable and stuff are in spanish, just replace them with what you need. In my case it's a table with 4 columns representing a date, a score, duration and max viewers.
private void fillJTable(){
//creating data to add into the JTable. Here you might want to import your proper data from elsewhere
Date date = new Date();
UserReplay rep1 = new UserReplay(date, 12, 13,14);
UserReplay rep2 = new UserReplay(date, 2,34,5);
ArrayList<UserReplay> usuaris = new ArrayList<>();
usuaris.add(rep1);
usuaris.add(rep2);
//----Filling Jtable------
DefaultTableModel model = (DefaultTableModel) view.getTable().getModel();
model.addColumn("Fecha");
model.addColumn("Puntuación");
model.addColumn("Tiempo de duración");
model.addColumn("Pico máximo de espectadores");
for (int i = 0; i < usuaris.size(); i++){
Vector<Date> fecha = new Vector<>(Arrays.asList(usuaris.get(i).getDate()));
Vector<Integer> puntuacion = new Vector<>(Arrays.asList(usuaris.get(i).getPuntuacion()));
Vector<Integer> tiempo = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Integer> espectadors = new Vector<>(Arrays.asList(usuaris.get(i).getTiempo()));
Vector<Object> row = new Vector<Object>();
row.addElement(fecha.get(0));
row.addElement(puntuacion.get(0));
row.addElement(tiempo.get(0));
row.addElement(espectadors.get(0));
model.addRow(row);
}
}
I have Two Function in Reducer Class : "reducer" and "execute". in "myExecute" function :
public class Reducer extends MapReduceBase
implements Reducer<IntWritable,Text, IntWritable, Text>, TIntProcedure
{
OutputCollector< IntWritable, Text> m_Collector = null;
RTree tree = new RTree();
private int m_BasePolyId;
private HashMap<Integer,PolyDefault> m_BasePolyMap = new HashMap<Integer,PolyDefault>();
private HashMap<Integer,PolyDefault> m_ClipPolyMap = new HashMap<Integer,PolyDefault>();
public void configure(JobConf conf)
{
//initialize the RTree
tree.init(null);
}
// the key is grid id and values are the polygon texts
public void reduce(IntWritable gridId, Iterator<Text> values,
OutputCollector<IntWritable, Text> collector, Reporter arg3)
throws IOException
{
m_Collector = collector;
List<PolyDefault>basePolyList = new ArrayList<PolyDefault>();
List<PolyDefault> overlayPolyList = new ArrayList<PolyDefault>();
Text clipText;
int count = 0;
String strcount = " ";
PolyDefault basePolygon = null;
String strBaseId;
String strClipId;
int baseId = 0;
int clipId = 0;
//values contain both basepolygons and clip polygons
PolyDefault clipPoly;
while(values.hasNext())
{
Text text = values.next();
if(text.charAt(0) == 'b')
{
basePolygon = new PolyDefault();
StringTokenizer baseItr = new StringTokenizer(text.toString());
//System.err.println("base : = " + baseText);
while (baseItr.hasMoreTokens()) // tokens are strings from one serialized polygon
{
if(count == 0)
{
baseItr.nextToken(); //discard
strBaseId = baseItr.nextToken(); //index or line number
baseId = Integer.parseInt(strBaseId);
Point2D lbox = new Point2D.Double(Double.parseDouble(baseItr.nextToken()), Double.parseDouble(baseItr.nextToken()));
basePolygon.setM_lbBox(lbox);
Point2D ubox = new Point2D.Double(Double.parseDouble(baseItr.nextToken()),Double.parseDouble(baseItr.nextToken()));
basePolygon.setM_ubBox(ubox);
}
count = count + 1;
double xCord,yCord;
xCord = Double.parseDouble(baseItr.nextToken());
yCord = Double.parseDouble(baseItr.nextToken());
Point2D vertex = new Point2D.Double(xCord,yCord);
basePolygon.add(vertex);
}
basePolyList.add(basePolygon);
m_BasePolyMap.put(baseId,basePolygon);
}
else
{
StringTokenizer clipItr = new StringTokenizer(text.toString());
clipPoly = new PolyDefault();
while(clipItr.hasMoreTokens())
{
if(count == 0)
{
//discard the index or line number
strClipId = clipItr.nextToken(); //index or line number
clipId = Integer.parseInt(strClipId);
Point2D lbox = new Point2D.Double(Double.parseDouble(clipItr.nextToken()), Double.parseDouble(clipItr.nextToken()));
clipPoly.setM_lbBox(lbox);
Point2D ubox = new Point2D.Double(Double.parseDouble(clipItr.nextToken()),Double.parseDouble(clipItr.nextToken()));
clipPoly.setM_ubBox(ubox);
Rectangle r2 = new Rectangle((float)lbox.getX(), (float)lbox.getY(), (float)ubox.getX(), (float)ubox.getY());
tree.add(r2, clipId);
}
count = count + 1;
double xCord,yCord;
xCord = Double.parseDouble(clipItr.nextToken());
yCord = Double.parseDouble(clipItr.nextToken());
Point2D vertex = new Point2D.Double(xCord,yCord);
clipPoly.add(vertex);
}
//overlayPolyList.add(clipPoly);
m_ClipPolyMap.put(clipId, clipPoly);
}
} //end while
Iterator<PolyDefault> itr = basePolyList.iterator();
Rectangle baseBox = new Rectangle();
PolyDefault basePoly;
while(itr.hasNext())
{
basePoly = itr.next();
baseBox.maxX = (float)basePoly.getM_ubBox().getX();
baseBox.maxY = (float)basePoly.getM_ubBox().getY();
baseBox.minX = (float)basePoly.getM_lbBox().getX();
baseBox.minY = (float)basePoly.getM_lbBox().getY();
this.m_BasePolyId = basePoly.getId();
tree.intersects(baseBox, this);
}
} //end reduce
public boolean execute(int clipPolyId)
{
PolyDefault basePoly = m_BasePolyMap.get(m_BasePolyId);
PolyDefault clipPoly = m_ClipPolyMap.get(clipPolyId);
PolyDefault resultPoly = (PolyDefault)Clip.intersection(basePoly, clipPoly);
String strResult;
if(resultPoly.isEmpty() == false)
{
strResult = Parser.serializePoly(resultPoly).toString();
try
{
m_Collector.collect(null,new Text(strResult) );
System.out.println(strResult);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return true;
}
}
map and reduce run completely , but in output(part-0000) , there is no message "Result Sucess ..." .
can I call Execute function in reducer or ... ?
Thanks
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>
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);
}
}
}