set drawable onImageview inside SimpleAdapter with hashmap

I’m trying to set drawable through simpleadapter

// looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    //String id = c.getString(TAG_PID);
                    //String name = c.getString(TAG_NAME);
                    String id = c.getString(TAG_SID);
                    String name = c.getString(TAG_NAME);
                    String size = c.getString(TAG_SIZE);
                    String type = c.getString(TAG_TYPE);
                    String created_at = c.getString(TAG_CREATED_AT);


                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                   // params.add(new Pair<>("TAG_SID", sid));
                   // params.add(new Pair<>("TAG_NAME", name));
                    map.put(TAG_SID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_SIZE, size);
                    map.put(TAG_TYPE,  type);
                    map.put(TAG_CREATED_AT, created_at);


                    // adding HashList to ArrayList
                    productsList.add(map);
                }

TAG_TYPE carries a drawable resource, for example, TAG_TYPE = R.drawable.css

and insert into sampleadapter like this

SimpleAdapter adapter = new SimpleAdapter(
                            ListFiles.this, productsList,
                            R.layout.list_row, new String[] { TAG_SID,
                            TAG_NAME,TAG_SIZE,TAG_TYPE,TAG_CREATED_AT},
                            new int[] { R.id.pid, R.id.title, R.id.duration, R.id.list_image, R.id.artist });

                    // updating listview
                    setListAdapter(adapter);

but i get this error when it happenas:

I/System.out: resolveUri failed on bad bitmap uri: b51b841b 10-07
 04:25:02.037 4292-4292/com.dattasolutions.dattacloud E/BitmapFactory:
 Unable to decode stream: java.io.FileNotFoundException:
 R.drawable.file: open failed: ENOENT (No such file or directory)

how do I set it right?

i have this on server side :

$age = array("video/avi"=>"R.drawable.avi", "text/css"=>"R.drawable.css", "application/msword"=>"R.drawable.doc", "application/octet-stream"=>"R.drawable.exe", "text/html"=>"R.drawable.html", "text/plain"=>"R.drawable.javascript", "image/jpeg"=>"R.drawable.jpg", "audio/mpeg3"=>"R.drawable.mp3", "application/pdf"=>"R.drawable.pdf", "image/png"=>"R.drawable.png", "application/mspowerpoint"=>"R.drawable.ppt", "text/plain"=>"R.drawable.txt", "application/excel"=>"R.drawable.xls", "text/xml"=>"R.drawable.xml", "application/zip"=>"R.drawable.zip");

so tag_type would be R.drawable.xml

Fetching data from mysql in tabbed activity crashes app

I tried to implement code to fetch data from an online mysql database and display it into a listview, in a fragment of a tabbed activity. However, whenever I launch the app it crashes. The code works without the tabbed activity fine.

The activity for the tabs

import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import semaj.mysqllogin.Tabs.Tab1Available;
import semaj.mysqllogin.Tabs.Tab2Employee;

public class TabbedActivity extends AppCompatActivity {

    ListView listView;

    private SectionsPagerAdapter mSectionsPagerAdapter;


    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabbed);

        listView = (ListView) findViewById(R.id.listview1);
        getJSON("**url to php**");

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

    }

    private void getJSON(final String urlWebService) {

        class GetJSON extends AsyncTask<Void, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
            }


            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
                try {
                    loadIntoListView(s);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected String doInBackground(Void... voids) {
                try {
                    URL url = new URL(urlWebService);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "n");
                    }
                    return sb.toString().trim();
                } catch (Exception e) {
                    return null;
                }
            }
        }
        GetJSON getJSON = new GetJSON();
        getJSON.execute();
    }

    private void loadIntoListView(String json) throws JSONException {
        JSONArray jsonArray = new JSONArray(json);
        String[] heroes = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            heroes[i] = obj.getString("name");
        }
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, heroes);
        listView.setAdapter(arrayAdapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_tabbed, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.menu) {
            startActivity(new Intent(this, Menu.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    Tab1Available tab1 = new Tab1Available();
                    return tab1;
                case 1:
                    Tab2Employee tab2 = new Tab2Employee();
                    return tab2;
                default:
                    return null;
            }

        }

        @Override
        public int getCount() {
            // Show 2 total pages.
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Available";
                case 1:
                    return "Employee";
            }
            return null;
        }
    }
}

One of the fragments

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import semaj.mysqllogin.R;



public class Tab1Available extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab1available,container,false);
        return rootView;
    }

}

The .xml layout for the activity for the tabs

    enter co<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="semaj.mysqllogin.TabbedActivity">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/appbar_padding_top"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay">

        </android.support.v7.widget.Toolbar>

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

Crash logs

10-07 22:10:10.821 5324-5324/semaj.mysqllogin E/AndroidRuntime: FATAL EXCEPTION: main
                                                            Process: semaj.mysqllogin, PID: 5324
                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                at semaj.mysqllogin.TabbedActivity.loadIntoListView(TabbedActivity.java:114)
                                                                at semaj.mysqllogin.TabbedActivity.access$000(TabbedActivity.java:32)
                                                                at semaj.mysqllogin.TabbedActivity$1GetJSON.onPostExecute(TabbedActivity.java:79)
                                                                at semaj.mysqllogin.TabbedActivity$1GetJSON.onPostExecute(TabbedActivity.java:66)
                                                                at android.os.AsyncTask.finish(AsyncTask.java:667)
                                                                at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                at android.os.Looper.loop(Looper.java:154)
                                                                at android.app.ActivityThread.main(ActivityThread.java:6321)
                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

10-07 22:10:10.821 5324-5324/semaj.mysqllogin D/AppTracker: App Event: crash

Tomcat doesn’t update an image

So I have a jsp page that displays some image from tomcat/webapps/AppName/imgs folder. I use Tomcat inside XAMPP.

<html>
    <body>
            <h1 align="center">Choosing a pet gift</h1>

            <img src="imgs/monkey.jpg"/>
            <p>
                    <%
                            List styles = (List) request.getAttribute("pets");
                            Map<String, String> petImgs = (Map) request.getAttribute("petImgs");

                            Iterator iter = styles.iterator();
                            while (iter.hasNext())  {
                                        out.println("<center>");
                                        out.println("<br>" + iter.next());
                                }
                                out.println("<br/>");

                                for (String value: petImgs.values())  {
                                    out.println("<img src="" + value + ""/>");
                                }
                                 out.println("</center>");
                    %>
            </p>
    </body>
</html>

I opened that image in Paint and edited it, but however when opened in a browser I still get the old image. I tried restarted Tomcat, restarting XAMPP neither works. The img in question is the only img with that name present in AppName folder.

How can I access a scanner object (the user’s input) in another class within the same package?

I have read through the questions and answers related to this topic but have not have found the answer that I need, or maybe understand. I am new at programming and I am learning Java. I am trying to use the scanner object from my main public class in a sub class of the sub class of the main public class. I know that I can only extend one class out.

Can anyone try to help me understand how to access this scanner object (the user’s input) in another class within the same package? I’m having trouble and this seems to be the only bug so far.

I keep getting the error “the value of the local variable ‘total’ is not used”. I am not using it “locally” I suppose, meaning in the same class. I am trying to access it in the other class.

this is the scanner object in my main class:

Scanner input = new Scanner(System.in);
    double total = input.nextDouble();

    System.out.println("Enter your total before tip: ");

    input.close();

Any ideas? I apologize if this is obvious, I can’t seem to figure it out at this point.

Thank you for your time and assistance.

SSL/TLS communication not happening with Tomcat Server on using self-signed certificate

I have configured Tomcat Server (apache-tomcat-9.0.1) with self-signed certificate. On this added required configuration on server.xml, and copied .jks file on conf folder.

Create Self Signed Certificate
Configure Tomcat with SSL Stuff

HTTPS Works on browser as expected.

disableSSL Verification while making HttpsURLConnection call to fetch an REST API

Certificate Exception Stuff
Disable Certificate Exception

It works ! –

On Server.xml -= only 8443 port configured.
On Web Application Security Constraint Configured:

<security-constraint>
    <web-resource-collection>
        <web-resource-name>OVS</web-resource-name>
        <!-- all URLs are protected -->
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <!-- redirect all requests to HTTPS -->
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>

Tomcat Server starts without showing any exception on anywhere.

But SSL/TLS communication not happening with Tomcat Server on using self-signed certificate , with Wireshark captured the packets , expected to see TLS Packets or SSL Handshake But nothing, Only TCP Packets.

Why SSL Handshake not happening ?, Its like because Its verifying only SSL server certificate ? ( as Client Authentication is false )

   <Connector SSLEnabled="true" acceptCount="100" clientAuth="false"
    disableUploadTimeout="true" enableLookups="false" maxThreads="150"
    port="8443" keyAlias="london" keystoreFile="conf/londonkey.jks" keystorePass="sumit123"
    protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https"
    secure="true" sslProtocol="TLS" /> 

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />

Have you ever tested after configuring the self-signed certificate etc stuff to see If SSL/TLS Communication take place ?

Java: Iris programming [on hold]

For this assignment, you will implement a simple machine learning algorithm called Nearest Neighbor which learns by remembering training examples.The learning will be done by remembering training examples stored in a comma-separated file. The training examples include different measurements which collectively are called attributes and a class label for different instances. The distance is computed using the following formula: 𝑑𝑖𝑠𝑡(𝑥, 𝑦) = √(𝑠𝑙𝑥 − 𝑠𝑙𝑦) 2 +(𝑠𝑤𝑥 − 𝑠𝑤𝑦) 2 + (𝑝𝑙𝑥 − 𝑝𝑙𝑦) 2 + (𝑝𝑤𝑥 − 𝑝𝑤𝑦) 2 where 𝑥, 𝑦 are two instances (i.e. a training or a testing example), 𝑠𝑙𝑥, 𝑠𝑙𝑦 are their sepal lengths, 𝑠𝑤𝑥, 𝑠𝑤𝑦 are their sepal widths, 𝑝𝑙𝑥, 𝑝𝑙𝑦 are their petal lengths, and 𝑝𝑤𝑥, 𝑝𝑤𝑦 are their petal widths.

Requirements create a program in Java that performs the following: 1. Loads and parses the training and testing dataset files into separate arrays (create four separate arrays) 2D array of doubles for storing training & testing example attribute value. 1D array of Strings for storing training & testing example class labels. You can assume there are exactly 75 training and 75 testing examples. 2. Classifies each testing example. You also need to output the true and predicted class label to the screen and save it into a new 1D array of Strings. This is done by iterating over the array of testing examples and computing the index of the closest training example. Then copying over the class label of the found training example into the new 1D array for the corresponding index. 3. Computes the accuracy

To Pick the First Airport Code from the Auto-populated list in Selenium with java

I have to automate the Flight page for the below URL

URL: https://www.expedia.co.in/Flights

Enter LAS in the ‘Flying From ‘ Textbox and you will see the list getting displayed and have to select the First Airport code from the auto-populated list matching the Airport Code .

I have to automate using Selenium with java. Could you share the piece of code for it.

Flight image with Autopopulated origin List

Beginner Needing Java Programming help! I can’t figure out how to go about solving this without if statement

“Given an amount of change less than one dollar, find the coins required to make up this amount. Your program should find the minimum number of coins. For example, if the change was $0.56, you would need 2 quarters, 1 nickel and 1 penny for a total of 4 coins. Hint: Use integer division and remainder.”

I have to write code for this on java for a school assignment. I can’t use an if statement to write a solution to this problem. Can anybody help me with this?

How do I get rid of StringIndexOutOfBoundsException in my code?

This is my first question on stackoverflow. I wanted to test myself and make a mini-programming language. But ever since I’ve decided to expand my code, I keep getting StringIndexOutOfBoundsExceptions. I’ve done some research here on stackoverflow and on youtube, and it seems like I am having a specific issue. Can you check it out please?
Thank you in advance…
PS: Sorry for confusing variable names, I’ve named it in my native language 😛
code:

import java.util.Scanner;
import java.util.Vector;

public class Komanda {
private String tip;
private String naziv;
private String parametar;
public Komanda() {
    super();
}
public Komanda(String tip, String parametar) {
    super();
    this.tip = tip;
    this.parametar = parametar;
}
public Komanda(String tip, String naziv, String parametar) {
    super();
    this.tip = tip;
    this.naziv = naziv;
    this.parametar = parametar;
}
public String getTip() {
    return tip;
}
public void setTip(String tip) {
    this.tip = tip;
}
public String getNaziv() {
    return naziv;
}
public void setNaziv(String naziv) {
    this.naziv = naziv;
}
public String getParametar() {
    return parametar;
}
public void setParametar(String parametar) {
    this.parametar = parametar;
}
}


public class Main {

public static void execute(Vector<Komanda> code) {
    for (int i = 0; i < code.size(); i++) {
        if (code.elementAt(i).getTip().equals("print:")) {
            if (!code.elementAt(i).getParametar().contains(":")) {
                System.out.println(code.elementAt(i).getParametar());
            } else {
                System.out.println("");
                System.out.print(code.elementAt(i).getParametar().substring(0,
                        code.elementAt(i).getParametar().indexOf(':') + 1));
                for (int k = 0; k < code.size(); i++) {
                    if (code.elementAt(k).getNaziv().equals(code.elementAt(i).getParametar()
                            .substring(code.elementAt(i).getParametar().indexOf(':') + 1))) {
                        System.out.print(" " + code.elementAt(k).getParametar());
                    }
                }
            }
        }
        if (code.elementAt(i).getTip().equals("var")) {

        }
    }
}

public static void main(String[] args){
    Vector<Komanda> code = new Vector<Komanda>();
    Scanner console = new Scanner(System.in);
    System.out.println("NNS 0.1 (v0.1.0:1, Oct  7 2017, 18:40:49) [MSC v.1900 64 bit]");
    for (int i = 0; i < 1;) {

        String line = console.nextLine();
        Scanner lineRreader = new Scanner(line);
        if (lineRreader.next().equalsIgnoreCase("SLC;")) {
            code.removeAllElements();
            line = line.substring(line.indexOf(';') + 2);
            if (line.equals("terminate")) {
                break;
            }
            if (lineRreader.next().equals("print:")) {
                System.out.println(line.substring(line.indexOf(':') + 2));
            }
            if (line.substring(0, line.indexOf(' ')).equals("print")) {
                line = line.substring(line.indexOf(' ') + 1);
                int firstNumber = lineRreader.nextInt();
                char operation = lineRreader.next().charAt(0);
                int secondNumber = lineRreader.nextInt();
                System.out.print(firstNumber + " " + operation + " " + secondNumber);
                switch (operation) {
                case '+':
                    int a = firstNumber + secondNumber;
                    System.out.print(" = " + (int) a);
                    break;
                case '-':
                    int b = firstNumber - secondNumber;
                    System.out.print(" = " + (int) b);
                    break;
                case '*':
                    int c = firstNumber * secondNumber;
                    System.out.print(" = " + (int) c);
                    break;
                case '/':
                    double d = firstNumber / secondNumber;
                    System.out.print(" = " + (double) d);
                    break;
                }
                System.out.println("");
            }

        } else {
            if (line.substring(0, line.indexOf(' ')).equalsIgnoreCase("print: ")) { // THIS IS THE 72ND LINE
                code.add(new Komanda("print:", line.substring(line.indexOf(' ')+1)));
            }
            else if (line.substring(0, line.indexOf(' ')).equalsIgnoreCase("var")) {
                code.add(new Komanda("var", lineRreader.next(),
                        line.substring(line.lastIndexOf(' ') + 1, line.length())));
            }
            else if (line.equalsIgnoreCase("exec")) {
                execute(code);
            }

        }
        lineRreader.close();
    }
    console.close();
}

}

MY CONSOLE OUTPUT:

NNS 0.1 (v0.1.0:1, Oct  7 2017, 18:40:49) [MSC v.1900 64 bit] <--STATUS STRING
print: helloworld <---- ME TYPING PRINT: COMMAND
exec <---- THIS IS THE COMMAND THAT TRIGGERS THE EXCEPTION
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String 
index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at Main.main(Main.java:72)