jeudi 30 juin 2016

For some reason when I put 'NameValuePair' it says cannot resolve symbol. How do I resolve this?

For some reason when I put 'NameValuePair' it says cannot resolve symbol. How do I resolve this?

The code:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int RESULT_LOAD_IMAGE = 1;

   ImageView imageToUpload, downloadedImage;
    Button bUploadImage, bDownloadImage;
    EditText uploadImageName, downloadImageName;

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

        imageToUpload = (ImageView) findViewById(R.id.imageToUpload);
        downloadedImage = (ImageView) findViewById(R.id.downloadedImage);

        bUploadImage = (Button) findViewById(R.id.bUploadImage);
        bDownloadImage = (Button) findViewById(R.id.bDownloadImage);

        uploadImageName = (EditText) findViewById(R.id.etUploadName);
        downloadImageName = (EditText) findViewById(R.id.etDownloadName);

        imageToUpload.setOnClickListener(this);
        bUploadImage.setOnClickListener(this);
        bDownloadImage.setOnClickListener(this);




}


    @Override
    public void onClick(View v) {
        switch(v.getId()){
            case R.id.imageToUpload:
                Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
                break;
            case R.id.bUploadImage:
                Bitmap Image = ((BitmapDrawable) imageToUpload.getDrawable()).getBitmap();




                break;
            case R.id.bDownloadImage:

                break;

        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode ==RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            imageToUpload.setImageURI(selectedImage);
        }

        }

        private class UploadImage extends AsyncTask<Void, Void, Void>{

            Bitmap image;
            String name;

            public  UploadImage(Bitmap image, String name) {
                this.image = image;
                this.name = name;
            }

            @Override
            protected void onPostExecute(Void aVoid) {

                super.onPostExecute(aVoid);
            }

            @Override
            protected Void doInBackground(Void... params) {
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

                ArrayList<NameValuePair> dataToSend = new ArrayList<>();
                dataToSend.add(new BasicNameValuePair("image"));


                return null;
            }
        }

    }

How do I solve the error of the 'NameValuePair'? Help will be appreciated in solving this error.

Thankyou

Java can't display Unicode block characters despite properly configured terminal

I'm trying to print the Unicode block character in a Java application being run in Cygwin. Despite the terminal being set to UTF-8, and despite Bash and Python being able to print the character, Java simply prints a ?.

$ echo $LANG
en_US.UTF-8

$ echo -e "xe2x96x88"
█

$ python3 -c 'print("u2588")'
█

$ cat Block.java
public class Block {
  public static void main(String[] args) {
    System.out.println('u2588');
  }
}

$ javac Block.java

$ java -cp . Block
?

This appears to be Cygwin-specific, as when run from cmd the character is displayed:

>java -cp . Block
█

Is there anything I can do to get Cygwin/mintty to render Java's output correctly?

Update:

It appears Java on Windows/Cygwin doesn't actually use the LANG environment variable, and is therefore actually still using cp1252:

$ cat Block.java
public class Block {
  public static void main(String[] args) {
    System.out.println("Default Charset=" + java.nio.charset.Charset.defaultCharset());
    System.out.println("u2588");
  }
}

$ java -cp . Block
Default Charset=windows-1252
?

But oddly I can't get iconv to work:

$ java -cp . Block | iconv -f WINDOWS-1252 -t UTF8
Default Charset=windows-1252
?

Is there any way (short of specifying -Dfile.encoding=UTF-8) to get Java to respect Cygwin's encoding? I'm also aware of JAVA_TOOL_OPTIONS, but this causes debugging output to be written to stderr. Not the end of the world, but not ideal.

Removing fragment from backstack on click of navigation drawer item

In my app I have a navigation drawer with several fragments. One of the menu from navigation drawer is for closing current visible fragment and go to previous one. To achieve above behavior I added fragment to backstack.

This is how my fragment transaction looks like

if (fragment != null) {
        fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container_body, fragment, "name");
        fragmentTransaction.addToBackStack(fragment.getClass().getSimpleName());
        fragmentTransaction.commit();

        // set the toolbar title
        getSupportActionBar().setTitle(title);
    }

I have added onBackPress() method to handle backstack transactions. Here is the code for backpress method.

@Override
public void onBackPressed() {
    if (fragmentManager.getBackStackEntryCount() > 0) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("name");

        fragmentManager.popBackStack();

        if (fragment instanceof Articulos) {
            mToolbar.setTitle("Articulos");

            // add your code to change title of toolbar
        } else if (fragment instanceof Clientes) {
            mToolbar.setTitle("Clientes");
        } else if (fragment instanceof Pedidos) {
            mToolbar.setTitle("Pedidos");
        } else if (fragment instanceof Herramientas) {
            mToolbar.setTitle("Herramientas");
        } else if (fragment instanceof Visor) {
            mToolbar.setTitle("Visor");
        }

    } else {

        super.onBackPressed();
    }
}

onBackPressed() method works properly as required when called on press of device back button . From navigation drawer menu for removing fragment from backstack, I have called this same method there also like this.

case 5:

            title = "Cerrar";
            onBackPressed();

            break;

PROBLEM: My problem is that when I call onBackPressed() from navigation drawer, it only pop first fragment from the backstack and not the remaining ones. I debugged this method and it is getting called properly but fragments are not changing after first time. I tried with popBackStackImmediate too but problem still remains. What can be the problem here?

Java homework - Creating and using enumerations

I have a little Java project that I was assigned where we're creating and using enumerations. The instructions for this portion of the project are:

  • In the Card class, modify the code so it uses the Suit enumeration as the type for the suit instance variable. (STUCK ON THIS STEP)
  • In the Main class, modify the displayCard method so it uses the Suit enumeration to check the suit of the card.
  • In the Main class, experiment by modifying the code that sets the suit and number for the Cart object. Note that you can’t set an illegal suit, but you can set an illegal number.
  • Run the application to make sure it works correctly.

I am not sure if it is the wording that is confusing me, or if its because there is not an example in the textbook that even remotely resembles this project, so it is throwing me off. I was able to do the initial setup leading up to these steps, but now I am stuck. Any help or guidance in the right direction is appreciated!

The code below is for the Suit enum, followed by the code for the Card class:

package murach.card;

public enum Suit {
	SPADES,
	HEARTS,
	DIAMONDS,
	CLUBS;
}

package murach.card;

public class Card {
    private int suit;
    private int number;
    
    public void setSuit(int suit) {
        this.suit = suit;
    }    
    
    public int getSuit() {
        return this.suit;
    }
    
    public void setNumber(int number) {
        this.number = number;
    }    
    
    public int getNumber() {
        return this.number;
    }
}

How do I increase the text size in my android textview based on loaded text?

I have a textview that displays text I load from a database. Sometimes the text is a single letter like b and sometimes it's two words that go over two lines like small word.

If I display a single letter I want the font size to be bigger. I tried using the html font tag with the size attribute and pass the string through Html.fromHtml():

<font size='6'>d</font>

However unfortunately the font size doesn't change and Android doesn't seem to recognize the attribute.

I don't want to give the font size in px because the I sometimes want to load the text in textviews with a different default textsize.


More detail: I have an app that asks the user a series of questions. To do so it displays two possible answers in two separate textviews. I have a few thousand questions in my database. The activity runs for 3 minutes at a time and I expect the user to answer a question every three seconds.

Sometimes the answer is a one-line word, sometimes it's take two lines and sometimes it's a single letter. In cases where it's a single letter I feel like I'm wasting space by displaying the letter in the same textsize, so I want to increase it's textsize.

In the field where the question is displayed, I have a similar issue. Sometimes the question takes two lines and sometimes it takes a short one-line word. When it takes one-line I also want to increase the font size.

How do you perform a HTTP POST in Java?

Recently I have been using an app on Chrome called Postman to perform HTTP POSTs for my convenience, but now I want to try doing this via Java instead because I want to make a program that sends various HTTP POSTs to a server and read/stores the response it returns to me.

In my Java code, I have this so far

import java.net.*;
import java.io.*;

class A {
    //A Java program to post and receive response
    public static void main(String[] args) throws Exception {

        String site = "http://username:password@192.168.0.10/data/info";

        URL url = new URL(site);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        String Body = "<Command><Name>Get_First_Name</Name></Command>"

        // How would I send this properly and read the response?

        System.out.print("The End");
    }
}

I have done some standard google searches, but I couldn't follow most of the answers since apparently there are multiple ways to do this and I never found a concrete method in the end. I believe I got the connection set up correct, but all that I couldn't digest into my brain was how to actually do the POST itself. It would be awesome if someone can guide me in the right direction with this.

REFERENCE: Here is a crop of Postman and what I put into it for my POSTs which is what I am now trying to do in Java because I don't want to rely on this app for the rest of my HTTP POSTs in the future.

enter image description here

savedInstanceState is always null, yet onSaveInstanceState() is always called

First of all I'm new to Android - this question could seem stupid :)

I've created an main Activity that contains a ViewPager. The ViewPager is linked to my ActionBar tabs. Currently my main Activity contains 3 tabs in this way.

My issue is the following: when I'm on the 3rd tab and create a new Activity and afterwards return to my main Activity I always return to my 1st tab.

I've tried the following approach in my main Activity:

// debugger breakpoints tell me this method is always called when other activity is shown ...
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    int pos = getActionBar().getSelectedNavigationIndex();
    outState.putInt("tab", pos);
}

// however, in onCreate() my savedInstanceState is always 'null' ...
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.invalidateOptionsMenu();

    setContentView(R.layout.activity_main);

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mViewPager
            .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(position);
                }
            });

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }

    // trying to restore state here, yet savedInstanceState is _always_ null ...
    if (savedInstanceState != null) {
        actionBar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    }
}

I've read that the savedInstanceState will always be null when there's no id defined. My XML layout has an id defined though, so this should not be an issue. I've also read that the 'onSaveInstanceState()` method should always call the method on the super class first, so I've implemented the method accordingly.

Anyone have any idea how to fix my issue? How to get the ViewPager to show the right tab / fragment when the main Activity is recreated?

Combo with ObservableMap Binding

I have a Combo populated using ObservableMap. What i want is if an item(key) is selected in combo, to be able to get corresponding object(value). This is what i have so far

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.logging.Level;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.ObservableMap;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import org.controlsfx.control.textfield.TextFields;

public class ComboWithHashMap extends Application{
    private ComboBox autocompleteCombo = new ComboBox();
    private ObservableMap<String, Member> list;
    public static void main(String[] args) {
       launch(args);
   }

@Override
public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Combo Sample");
    primaryStage.setWidth(450);
    primaryStage.setHeight(550);

    list = FXCollections.observableMap(getActiveMember());
    autocompleteCombo.getItems().setAll(list.keySet());
    TextFields.bindAutoCompletion(autocompleteCombo.getEditor(), autocompleteCombo.getItems());
    Scene scene = new Scene(new BorderPane(autocompleteCombo), 880, 600);
    primaryStage.setScene(scene);
    primaryStage.show();
}


public HashMap<String, Member> getActiveMember(){
    HashMap<String, Member> map = new HashMap<String, Member>();
    Member member1 = new Member(1, "123", "John Doe");
    Member member2 = new Member(1, "234", "Sally Doe");
    Member member3 = new Member(1, "345", "Billy Doe");

    map.put( member1.getMilkNo(), member1);
    map.put( member2.getMilkNo(), member2);
    map.put( member3.getMilkNo(), member3);

    return map;
}

public class Member {
private int id;
private String milkNo;
private String fullName;

public Member(int id, String milkNo, String fullName) {
    this.id = id;
    this.milkNo = milkNo;
    this.fullName = fullName;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}


public String getMilkNo() {
    return milkNo;
}

public void setMilkNo(String milkNo) {
    this.milkNo = milkNo;
}

@Override
public String toString() {
    return fullName;
}

 }

}

The problem is so far i cannot get the corresponding object(value) when a key is selected.

GLSL : Accessing an array in a for-loop hinders performance

Okay, so I'm developing an android app for a game I'm making (with LibGDX). And I have a fragment shader and I noticed that I had ~41 FPS. I was playing around with the code to see where the problem was, and I saw that changing how I accessed an array from arrayName[i] to arrayName[0] increased the performance back to 60 FPS, even though the loop only iterated once in this specific instance.
Here's the code :

#version 300 es

precision highp float;

uniform sampler2D u_texture;

in vec2 vTexCoord0;

struct BlackHole {
    vec2 position;
    float radius;
    float deformRadius;
};

uniform vec2 screenSize;
uniform vec3 cameraPos;
uniform float cameraZoom;

uniform BlackHole blackHole[4];
uniform int count;

out vec4 fragColor;

void main() {
    vec2 pos = vTexCoord0;

    bool doSample = true;

    for (int i = 0; i < count; i++) {
        vec2 position = (blackHole[i].position - cameraPos.xy) / cameraZoom + screenSize*0.5; // <--------
        float radius = blackHole[i].radius / cameraZoom; // <-------- blackHole is the array, and changing from [i] to [0]
        float deformRadius = blackHole[i].deformRadius / cameraZoom; // <--------

        vec2 deltaPos = vec2(position.x - gl_FragCoord.x, position.y - gl_FragCoord.y);
        float dist = length(deltaPos);

        if (dist <= radius) {
            fragColor = vec4(0, 0, 0, 1);
            doSample = false;
            break;
        } else if (dist <= radius + 1.0) {
            fragColor = vec4(1);
            doSample = false;
        } else if (dist <= deformRadius) {lensing
            float distToEdge = deformRadius - dist;
            pos += distToEdge * normalize(deltaPos) / screenSize;
        }
    }

    if (doSample)
        fragColor = texture(u_texture, pos);
}

In this specific case, "count" is 1.
Is this just an intrinsic property of GLSL? Or is there some fix to it – the highest value of "count" would be 4, so I could expand it out and not use a for loop, but I feel like that isn't a very good solution.
So, does anyone know why this is happening and/or a way to fix it?

IntentService from another Application


I would be very grateful if you help me to understand where I made a mistake in the code.
I have two applications.
App1 has activity with buttons which start and stop the service from App2.
App2 has no activity. It has only Java class with Service.
I will be very thankful for any comments and answers.

Thanks!

App1 (Activity):

public class MainActivity extends AppCompatActivity {

Intent intent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    intent = new Intent("com.example.timbook.myservice.MService");
}

public void onClickStart (View v) {
    startService(intent);
}

public void onClickStop (View v) {
    stopService(intent);
}
}

App1 (Manifest):

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

App2 (Service):

public class MService extends Service{

MediaPlayer mp;

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    mp = MediaPlayer.create(this,R.raw.glassanimals);
    mp.start();
}
}

App2 (Manifest):

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

    <service
        android:name="com.example.timbook.myservice.MService"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="com.example.timbook.myservice.MService"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>

    </service>

</application>

How to properly setup documentation for Restful services in a micro-service architecture (HAL, ALPS)

I have been reading a lot about how to setup Microservices properly and I have been getting hung up with some of the more recent concepts including: HAL, ALPS, and the HAL Browser. I have historically documented things leveraging Swagger UI, however, I am coming to understand that URL centric isn't the proper way and I should be organizing documentation around resources and links which is what the newer technologies are for. I have quite a few knowledge gaps around these newer concepts, so I wanted to get a proper understanding of how these technologies work together so as I learn about each I can fit them into the puzzle.

My current understanding is:

HAL - Is an additional format on top of JSON that will let you navigate through your API via links.

ALPS - It is an additional format on top of JSON that can let me provide English based descriptions to help describe my resources

HAL Browser - Swagger UI replacement for Resource and Link centric documentation. Works with both HAL and ALPS together?

Would my current understanding of these technologies be accurate or lacking in some areas? Also implementation wise I am not fully understanding how the ALPS and HAL are interacting together. I was aware of a hal+json format and a alps+json format, but I haven't seen a hal+alps+json format.

The last area I would like to clear up is how I should be exposing these resources. Typically I always had a focus on very lean json messages is sending the hal+json format around the expected or should I be hosting those endpoints at another URL specifically for documentation similar to swagger / HAL browser?

Error in reading data from InputStream in Bluetooth on Android

I'm working on an Android app, which uses bluetooth connection to transfer data between my android smartphone and a non-android bluetooth module, using SPP profile. I've used Bluetooth Chat Example from Android Developer site as reference.

I've successfully made two devices connect to each other and sent simple strings from the smart phone to the bluetooth module. But I've got some error in reading data sent back from the module. I've used the following code, which is exactly the same as in Bluetooth Chat Example, to read data from InputStream

while (true) 
{
                try {
                    // Read from the InputStream
                    bytes = mmInStream.read(buffer);
                    String str = new String(buffer);
                    Log.i(TAG, "mmInStream - " + str);
                    // Send the obtained bytes to the UI Activity
                    mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                } catch (IOException e) {
                    Log.e(TAG, "disconnected", e);
                    connectionLost();
                    break;
                }
            }

When my bluetooth module send a simple string to the phone, that string is not received correctly. It is splited into several pieces in random ways. For example, if I send "1234567890abcdef1234567890abcdef0123456789" for three times to the phone, the Logcat on Eclipse will log these:

mmInstream - 12345678910abcdef��������(continuing null)
mmInstream - 1��������(continuing null)
mmInstream - 2345678910abcdef0123456789��������(continuing null)

for the first time. In the second and the third time data is transmitted, it is received in a difference pieces:

mmInstream - 1234567891�������(continuing null)
mmInstream - 0abcdef012�������(continuing null)
mmInstream - 3456789���������(continuing null)

mmInstream - 1234567891����������������(continuing null)
mmInstream - 0abcdef0123456789������������(continuing null)

I don't know why this happen and how to solve this problem. If data is received in a arbitrary way like this, I can't get necessary data to process. How can I get it in one pieces?

Any help would be appreciated.

Many Thanks.

Navigation drawer manipulation within the App [Is it Possible?]

Or "how can I create additions to the navigation drawer from the app itself"

Hi.

What I am doing: I am creating an app in which led lights can be controlled using bluetooth and user can add multiple devices (in the snaps ,I call them rooms , but it is actually devices(one per room)] to access it instantaneously using the inbuilt remote. what it looks like:

What I want to do: As you may see there is an add button on the navigation drawer. I have created the activity for that [right now it is just a mock up in which you add name of device/room and a pin and it should show on the navigation drawer]. After adding , I want the new entry to appear below the old entries, something like this: What it should look like

Also every time I open the app , the app reads from the db and shows all the previously added devices/rooms

How do I proceed to make such an app and how can I create additions to the navigation drawer from the app itself? I am a new android dev and this is my first app.

While answering , you can assume my familiarity with Java , mysql and Android. All I want to know is how must I proceed with this.

I don't have anyone to help me out , so any help will be greatly appreciated!

Thank you!!

Syntax Errors on Start of Method and in Array [duplicate]

This question already has an answer here:

import java.util.Random;
import java.util.Scanner;

public class BennettsWords 
{
    public static String input1;
    public static  Scanner input=new Scanner(System.in);

    public static String [] sen1 = new  String [9]
    sen1 [0]="Wanna gooo!!!";
    sen1 [1]="I'm very disapointed with you, I might have to throw you out of the window!";

    public static String SM1="Wanna gooo!!!";
    public static String SM2="I'm very disapointed with you, I might have to throw you out of the window!";
    public static String SM3="BiggThinggg";
    public static String SM4="Boy...Boyy";
    public static String SM5="Ohh..Joel With the Big Thingg";
    public static String SM6="Ohh..Sargis With the Big Thingg";
    public static String SM7="Ccccbooyy";
    public static String SM8="Aowowwowo";
    public static String SM9="Your Mamama last Night...awawawawaw";
    public static String SM10="Omagow";

    public static void main(String[]args)
    {
        System.out.println("What he gonna say(Type Hear It)");
    String input1= input.nextLine();
    if (input1.equals("Hear It")||input1.equals("Hear it")||input1.equals("hear it"))
    {
        Random statement= new Random();
        System.out.println();
    }
}
}

In lines 10,24 some Syntax error appears Line 10= Multiple markers at this line - Syntax error on token "sen1", delete this token - Syntax error on token ";", { expected after this token

Line 24= Multiple markers at this line - Syntax error on token ")", ; expected - Syntax error on token "(", ; expected

I checked this error in a post and it was said that this is a Eclipse bug. I am a beginner so I don't know if it is a bug or my program. I run Eclipse neon Please inform me and if it is a bug please tell me what to do Thank You

spring-boot application fails to start

I recently start to develop a web application with spring-boot, anf, following the guide in the offical site, manage to create this two files:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>spring</groupId>
  <artifactId>app</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>app</name>
  <url>http://maven.apache.org</url>

  <properties>
    <start-class>com.spring.app.Application</start-class>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.1.8.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

</project>

Application.java

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {

    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(Application.class, args);

        System.out.println("Let's inspect the beans provided by Spring Boot:");

        String[] beanNames = ctx.getBeanDefinitionNames();
        Arrays.sort(beanNames);
        for (String beanName : beanNames) {
            System.out.println(beanName);
        }
    }

}

but when I try run the application with java -jar appname i get the error: Cannot find the main class: com.spring.app.Application. Program will exit, and in the terminal: Exception in thread "main" java.lang.NoClassDefFoundError: com/spring/app/Application.

What I am doing wrong?

FCM not open necessary Activity when app is closed

Sorry for my english. Before i use GCM for push notoifications and i have one problem when my app is closed and i click on notification opened only mainactivity.class not the one that I put for when click notification is open necessary activity. The problem was that i extends in GcmListenerService like documentation I decided it when extends IntentService and its was work. When my app is closed and i click on notification opened necessary activity.

Then i want got to FCM and i have same problem when i extends on GcmListenerService but now i extends on FirebaseMessagingService and now like before i cant open necessare activity when app is closed.

Before(when all work file) in manifest i have (GcmMessageHandler - my push class)

<receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.nga.plancentral" />
            </intent-filter>
        </receiver>

        <service android:name="push.GcmMessageHandler"  
           android:exported="false" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
            </intent-filter>
        </service>

        <meta-data android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" /> 

Now in manifest i have

 <service
        android:name="push.FBMnotification">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>

Why is my Spring @Autowired field returns null?

This is not a duplicate of this question. So please don't close it for "is duplicate of" reasons..


I'm trying to autowire a bean into the java class. My problem is that playerDAO remains null and does not get initialized.

mvc-dispatcher-service.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:component-scan base-package="ngdemo"/>

    <mvc:annotation-driven/>

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>    
</beans>

PlayerDAO.java

@Repository
@SuppressWarnings({"unchecked", "rawtypes"})
public class PlayerDAO {
    @Autowired
    private SessionFactory sessionFactory;

    @Transactional
    public Player getPlayerByUsername(String username) {
      //some code
    }
}

LoginRestService.java

@Path("/v1")
@Controller
public class LoginRestService {

    @Autowired
    private PlayerDAO playerDAO;

    @Path("/login")
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username,
                                     @FormParam("password") String password, @Context UriInfo request) {
     playerDAO.getPlayerByUsername(username);
     //NPE, playerDAO here is null when I'm trying to access it
    }    
}

What am I missing?

Full code available here: https://github.com/Ferenus/hestalis

Can not connect my android project with parse-dashboard locally

Am trying to connect my android program to the parse server dashboard. i have created the dashboard successful, i have tried searching everywhere, but its like there telling me d same thing i have done, here is my code thank u..`

****StarterApplication.java****

    package com.parse.starter;

    import android.app.Application;
    import android.util.Log;

    import com.parse.Parse;
    import com.parse.ParseACL;
    import com.parse.ParseException;
    import com.parse.ParseObject;
    import com.parse.ParseUser;
    import com.parse.SaveCallback;


    public class StarterApplication extends Application {

      @Override
      public void onCreate() {
        super.onCreate();

        // Enable Local Datastore.
        Parse.enableLocalDatastore(this);

        // Add your initialization code here
        Parse.initialize(new Parse.Configuration.Builder(getApplicationContext())
                .applicationId("instagram99n990nm900b")  //application id
                .clientKey("instagjusohjwjikkjjoeoeh")  //master key
                .server("https://instagram914.herokuapp.com/parse/")  //serverURl
        .build()
        );

          ParseObject gameScore = new ParseObject("GameScore");
          gameScore.put("score", 1337);
          gameScore.put("playerName", "Sean Plott");
          gameScore.put("cheatMode", false);
          gameScore.saveInBackground();
          gameScore.saveInBackground(new SaveCallback() {
              public void done(ParseException e) {
           if (e == null) {
                      Log.i("Parse", "Save Succeeded");
                  } else {
                      Log.i("Parse", "Save Failed");
                  }

              }
          });


          ParseUser.enableAutomaticUser();
        ParseACL defaultACL = new ParseACL();
        // Optionally enable public read access.
        // defaultACL.setPublicReadAccess(true);
        ParseACL.setDefaultACL(defaultACL, true);
      }
    }

    **MainActivity.java**

    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;

    import com.parse.ParseAnalytics;


    public class MainActivity extends ActionBarActivity {

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

        ParseAnalytics.trackAppOpenedInBackground(getIntent());
      }

      @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_main, 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.action_settings) {
          return true;
        }

        return super.onOptionsItemSelected(item);
      }
    }

Image is not displaying propertly

I am trying to make 2D array of JPanels that will contain images. Everything compiles well, but the last square in the bottom right corner. I was trying to fix this, but as I see for me it's impossible. This is the code that I actually have:

ImagePanel.java:

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {
    private static final long serialVersionUID = 1423049366366931156L;
    private BufferedImage image;

    public ImagePanel(BufferedImage i) {
        image = i;
        this.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
    }

    public void newImage(BufferedImage i) {
        image = i;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

As You see, my ImagePanel class is well. Thats how i declare it:

final int BOARD_X = 25;
final int BOARD_Y = 15;
ImagePanel[][] PanelBoard = new ImagePanel[BOARD_X][BOARD_Y];

And I fill (and add to form) afterwards using the following code:

for (int i = 0; i < BOARD_Y; ++i) { //y
    for (int i2 = 0; i2 < BOARD_X; ++i2) { // x
        PanelBoard[i2][i] = new ImagePanel(textures[0]);
        PanelBoard[i2][i].setBounds(i2 * 48, i * 48, 48, 48);
        PanelBoard[i2][i].setVisible(true);
        add(PanelBoard[i2][i]);
    }
}

The textures array is simply an array that contains arrays of buffered images (that are actually loaded properly).

Everything seems to look good, but the last square doesn't show.

So, my question is: how can I make this code work, and properly display the last square in the bottom right corner?

EDIT:

This code fixed my problem, but I cant figure out why:

PanelBoard[BOARD_X-1][BOARD_Y-1] = new ImagePanel(textures[0]);
        PanelBoard[BOARD_X-1][BOARD_Y-1].setBounds(BOARD_X*48, BOARD_Y*48, 48, 48);
        PanelBoard[BOARD_X-1][BOARD_Y-1].setVisible(true);
        add(PanelBoard[BOARD_X-1][BOARD_Y-1]);

NameNotFoundException in addParentStack

I am trying to build a notification and display it and also build a stack to the intent which I am displaying. But i get a NameNotFoundException.

Intent resultIntent = new Intent(mContext, ForecastFragment.class);

TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
stackBuilder.addParentStack(ForecastFragment.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.
                    getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
                    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(10 ,mBuilder.build());

Here is the exception that I get.

3541-3562/com.example.android.sunshine.app E/AndroidRuntime: FATAL EXCEPTION: SyncAdapterThread-1
          Process: com.example.android.sunshine.app, PID: 3541
          java.lang.IllegalArgumentException: android.content.pm.PackageManager$NameNotFoundException: ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.ForecastFragment}
             at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:247)
             at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:226)
             at com.example.android.sunshine.app.sync.SunshineSyncAdapter.notifyWeather(SunshineSyncAdapter.java:526)
             at com.example.android.sunshine.app.sync.SunshineSyncAdapter.getWeatherDataFromJson(SunshineSyncAdapter.java:424)
             at com.example.android.sunshine.app.sync.SunshineSyncAdapter.onPerformSync(SunshineSyncAdapter.java:255)
             at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:259)
          Caused by: android.content.pm.PackageManager$NameNotFoundException: ComponentInfo{com.example.android.sunshine.app/com.example.android.sunshine.app.ForecastFragment}
             at android.app.ApplicationPackageManager.getActivityInfo(ApplicationPackageManager.java:314)
             at android.support.v4.app.NavUtils.getParentActivityName(NavUtils.java:301)
             at android.support.v4.app.NavUtils.getParentActivityIntent(NavUtils.java:256)
             at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:240)
             at android.support.v4.app.TaskStackBuilder.addParentStack(TaskStackBuilder.java:226) 
             at com.example.android.sunshine.app.sync.SunshineSyncAdapter.notifyWeather(SunshineSyncAdapter.java:526) 
             at com.example.android.sunshine.app.sync.SunshineSyncAdapter.getWeatherDataFromJson(SunshineSyncAdapter.java:424) 
             at com.example.android.sunshine.app.sync.SunshineSyncAdapter.onPerformSync(SunshineSyncAdapter.java:255) 
             at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:259)

I checked the Package name and the package where the class ForecastFragment is placed but it is all correct. Can someone please help me out in sorting this one.

Android scrolling function in cardView + RecyclerView layout

In my application I have first the cardview and then RecyclerView. Using my existing code I am able to scroll the whole page. But I want that I can also scroll only the card view items. Currently when I try to scroll cardview the complete layout is scrolled.

Picture

My current code:-

<android.support.design.widget.AppBarLayout
    android:id="@+id/app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">


    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_scrollFlags="scroll|exitUntilCollapsed"
        app:contentScrim="?attr/colorPrimary"
        app:expandedTitleMarginStart="48dp"
        app:expandedTitleMarginEnd="64dp"
        android:fitsSystemWindows="true">

        <android.support.v7.widget.CardView style="@style/Card">

            <LinearLayout style="@style/CardContainer"
                android:isScrollContainer="true">


                    <com.greenfrvr.hashtagview.HashtagView
                        android:id="@+id/hashtags6"
                        style="@style/HashtagView"
                        app:rowGravity="center"
                        app:rowMode="stretch"
                        app:selectionMode="true"
                        app:tagBackground="@drawable/item_bg_1"
                        app:tagForeground="@drawable/flat_button_light"
                        app:tagPaddingBottom="@dimen/padding_vertical"
                        app:tagPaddingLeft="@dimen/padding_horizontal"
                        app:tagPaddingRight="@dimen/padding_horizontal"
                        app:tagPaddingTop="@dimen/padding_vertical"
                        app:tagTextColor="#E5E5E5" />



            </LinearLayout>
        </android.support.v7.widget.CardView>




        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_collapseMode="pin" />

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


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




    <android.support.v7.widget.RecyclerView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

How do I make scaled images look better in Java/OpenGL?

Here are two pictures of the same image:

this is what it looks like when viewed in preview...

and this is how it looks in my game...

enter image description here

Obviously the character is scaled down in my game, however, when I scale down the sprite in preview or pixelmator, it is still smooth. Even when the image is at a 1:1 scale it still has the jagged edges.

This is my render method

public void render(Camera camera, List<Entity> entities) {
    shader.loadViewMatrix(Main.createViewMatrix(camera));

    //per textured model
    GL30.glBindVertexArray(((RenderComponent) entities.get(0).getComponent(EntityComponentType.RENDER)).texturedModel.getRawModel().getVaoID());
    GL20.glEnableVertexAttribArray(0);
    GL20.glEnableVertexAttribArray(1);

    for(Entity e : entities) {
        RenderComponent render = (RenderComponent) e.getComponent(EntityComponentType.RENDER);

        //load transformation matrix per entity
        shader.loadTransformationMatrix(Main.createTransformationMatrix(render.position, render.rx, render.ry, render.getScaleX(), render.getScaleY()));
        shader.loadSprite((AnimationComponentContainer) e.getComponent(EntityComponentType.ANIMATION));

        //activate texture for each entity
        GL13.glActiveTexture(GL13.GL_TEXTURE0);
        GL11.glBindTexture(GL11.GL_TEXTURE_2D, render.getTexturedModel().getTexture().getTextureID());

        //render entity
        GL11.glDrawElements(GL11.GL_TRIANGLES, render.getTexturedModel().getRawModel().getVertexCount(), GL11.GL_UNSIGNED_INT, 0);
    }

    //per textured model
    GL20.glDisableVertexAttribArray(0);
    GL20.glDisableVertexAttribArray(1);
    GL30.glBindVertexArray(0);
}

And in my fragment shader I sample the image

vec4 color = texture(sampler, pass_TextureCoords);

and remove transparency

if(color.a < 0.5) discard;
out_Color = vec4(totalDiffuse, 1) * color;

My question is, how do I prevent the jagged edges from occurring (they are most prominent around his pants)? Or how do I smooth them out? The image itself if 512x1024

Saving ArrayList to Text File

I have been trying to get an ArrayList to save to a file. I can see it is creating the text file, but nothing is placed inside the text file, just blank.

Here is the main code with the ArrayList,Switch with option to save.

static int input, selection, i = 1;
static ArrayList<Animals> a;

// Main Method
public static void main(String[] args){

    // Create an ArrayList that holds different animals
    a = new ArrayList<>();
    a.add(new Animals(i++, "Bear", "Vertebrate", "Mammal"));
    a.add(new Animals(i++, "Snake", "Invertebrate", "Reptile"));
    a.add(new Animals(i++, "Dog", "Vertebrate", "Mammal"));
    a.add(new Animals(i++, "Starfish", "Invertebrates", "Fish"));

    while (true) {
        try {
            System.out.println("nWhat would you like to do?");
            System.out.println("1: View Listn2: Delete Itemn3: Add Itemn4: Edit Itemn5: Save Filen0: Exit");
            selection = scanner.nextInt();
            if(selection != 0){
                switch (selection) {
                    case 1:
                        ViewList.view();
                        Thread.sleep(4000);
                        break;
                    case 2:
                        Delete.deleteItem();
                        Thread.sleep(4000);
                        break;
                    case 3:
                        Add.addItem();
                        Thread.sleep(4000);
                        break;
                    case 4:
                        Edit.editItem();
                        Thread.sleep(4000);
                        break;
                    case 5:
                        Save.saveToFile("animals.txt", a);
                        Thread.sleep(4000);
                        break;

This is what I have written to handle file.

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;

public class Save extends ALProgram{
     public static void saveToFile(String fileName, ArrayList list){
            Path filePath = Paths.get(fileName);
            try{
                System.out.println("File Saved");
                Files.write(filePath, list, Charset.defaultCharset());
            }catch(IOException e){
                e.printStackTrace();
            }

     }
}

Here is Animal Class

class Animals {

public int id;
public String type, vertebrate, aclass;

public Animals(int id, String type, String vertebrate, String aclass) {
    this.id = id;
    this.type = type;
    this.vertebrate = vertebrate;
    this.aclass = aclass;

}

public int getID() {
    return id;
}

public String getType() {
    return type;
}

public String getVert() {
    return vertebrate;
}

public String getaclass() {
    return aclass;
}

}

Service not starting after boot device

I have a problem with running the service. In the logs there is nothing to see that the service is running. So I don't know that she works. Toast also does not show in MainActivity. I read a lot of posts and none work. How to fix it?

Service

import android.app.Service;
import android.os.IBinder;
import android.widget.Toast;
import android.content.Intent;

public class AutoStartUp extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        // do something when the service is created
    }

}

BroadcastReceiver

import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;

public class BootComplete extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
            Intent serviceIntent = new Intent(context, AutoStartUp.class);
            context.startService(serviceIntent);
        }

    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kamiszczu.ovh.servicetest3">
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" >
    </uses-permission>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver
            android:name="kamiszczu.ovh.servicetest3.BootComplete"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <service
            android:name="kamiszczu.ovh.servicetest3.AutoStartUp"
            android:enabled="true">
        </service>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Adapting dependencies after downgrading Google Play Sevices

What should I compile instead of:

compile 'com.google.android.gms:play-services:9.0.2'
compile 'com.google.android.gms:play-services-maps:9.0.2'
compile 'com.google.android.gms:play-services-location:9.0.2'
compile 'com.google.android.gms:play-services-base:9.0.2'
compile 'com.android.support:multidex:1.0.0'

in my dependencies in build.gradle (Module:app) when I downgraded Google Play Services from 9.0.83 to 8.1.18 manually? My purpose was to avoid this log error:

06-24 18:50:24.488 7128-7759/com.noureddine_ouertani.www.wocelli50 E/DynamiteModule: Failed to load module descriptor class: Didn't find class "com.google.android.gms.dynamite.descriptors.com.google.android.gms.googlecertificates.ModuleDescriptor" on path: DexPathList[[zip file "/data/app/com.noureddine_ouertani.www.wocelli50-2/base.apk"],nativeLibraryDirectories=[/vendor/lib64, /system/lib64]]

@Er. Arjun saini : I get this error. (My Manifest file was correctly configured.)

enter image description here

I'm trying to clean with the following build.gradle now:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.noureddine_ouertani.www.wocelli50"
        minSdkVersion 19
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    dexOptions {
        //incremental = true;
        preDexLibraries = false
        javaMaxHeapSize "4g"
    }
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:support-annotations:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
//compile 'com.google.android.gms:play-services:9.0.2'
//compile 'com.google.android.gms:play-services-maps:9.0.2'
//compile 'com.google.android.gms:play-services-location:9.0.2'
//compile 'com.google.android.gms:play-services-base:9.0.2'
//compile 'com.android.support:multidex:1.0.0'

compile 'com.android.support:multidex:1.0.1'

compile 'com.google.android.gms:play-services:+' //remove others instead of

}

What is the good way to create alertdialog with checkbox and seekbar in android?

How to create alert dialogs with or without xml as per image below ? sample code will help.

  1. Seekbar is disabled when checkbox is checked.

alertDialog with checkbox and seekbar

For this dialog, I was able to create some short of dialog but, I am not sure how to place check box and its logic if checkbox is checked/uncheckd, seekbar needs to disabled/enabled.

public void ShowDialog()
{
    final AlertDialog.Builder popDialog = new AlertDialog.Builder(this);
    popDialog.setPositiveButton("OK",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    popDialog.setNegativeButton("Cancel",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    final SeekBar seek = new SeekBar(this);
    seek.setMax( ... );
    seek.setProgress(...);
    final AlertDialog handle = popDialog.create();

    handle.setIcon(android.R.drawable.ic_menu_preferences);     
    handle.setTitle("Brighness"); 
    handle.setView(seek);

    seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser){
            //Log.d(TAG, "Value of : " + value);
        }

        public void onStartTrackingTouch(SeekBar arg0) {
            //Log.d(TAG, "onStartTrackingTouch");
        }

        public void onStopTrackingTouch(SeekBar seekBar) {
            //Log.d(TAG, "onStopTrackingTouch");
        }
    });
    handle.show();      
}
  1. Auto line is dimmed when seekbar is highlighted.

Auto dimmed, seekbar highlighted

  1. seekbar is dimmed when Auto line is highlighted.

Auto highlighted, seekbar dimmed

I have checked other questions, those are more about custom dialogs : How to create a Custom Dialog box in android? But, None of these are giving me clear idea so, I am asking this specific question.

mercredi 29 juin 2016

back button behavior in android in appcelerator alloy application

I am having trouble understanding the back button behavior in my alloy application in android. The scenario is this:

I am loading a widget in one of my windows to which I pass some parameters to use. I am retrieving these arguments in the standard way:

var args = arguments[0] || {};

On window close, I am setting the args to null. Now, this works fine as long as I close the window using my close button. args is set to null, and re-instantiated when I open the window again.

When I close the window with back button, args is set to null, but is never re-instantiated once I open the window again, and remains null. I have checked this with both heavyweight and light windows.

What all things does back button do? How can I enable re-instantiation of all the arguments again on opening the window?

Code: index.xml

<Alloy>
    <Window id="myWin" class="container">
        <View layout="vertical">
            <Require type="widget" src="myWidget" id="myWidget" title='mainWindow' close='mainWindow' />
        </View>
    </Window>
</Alloy>

index.js:

// setting args to null on window close
$.myWin.addEventListener('close', function () {
    $.myWidget.resetData();
});

Inside myWidget's controller, widget.js:

var args = arguments[0] || {};

// sets args to null
function resetData() {
    args = null;
}

exports.resetData = resetData;

The above code does not re-initiate args once set to null (when we close window with back button). If however, I export args and set it to null in window controller, it shows there that args is null, but args has all the data once we re-open the window again even though it is not initiated again.

Code: index.js

$.myWin.addEventListener('close', function () {
    $.myWidget.args = null;
});

Inside myWidget's controller, widget.js:

exports.args = args;

What exactly is going on here?

How do I correctly implement Immersive Full-Screen Mode in Android?

I have an application where I have a single activity that contains layers of fragments. I wanted to Switch between Immersive mode and Normal mode during some states of the app. Everything was fine until I call Hide System UI as per Android Documentation

Documentation Code

The sizes of the fragments started to go weird. No solutions found in stack overflow was any help.

I have uploaded the project to GitHub . Could you please provide some insights on what I am doing wrong?

  1. Project When Started Step One

  2. When another Fragment was added to the same FrameLayout

Step Two

  1. When Third fragment was added to another FrameLayout while Immersive mode is triggered

Step 3

  1. Problem begins When Third Fragment's View minimised we trigger "Normal Mode". The top and bottom of the Previous fragments were cut out. Step 4

Moreover, Go Full Screen, Rotate and then Tap tap on PIP. It gets more ugly.

I have uploaded the project to GitHub . Could you please provide some insights on what I am doing wrong?

Listview not updating after arraylist is updated?

I've seen many other posts in this context, but none helped. Problem is when i click on the addField button, the listview inside dialog adds new view just once. But at other clicks it doesn't get updated though The adapter works correctly (I mean the getView is called and also the arrayList in the adapter is changed in size).

I've used notifyDataSetChanged() in the adapter class. No result! I used an instance of adpater class in activity and called myAdapter.notifyDataSetChanged(). No result!

here is my code:

public class MainActivity extends Activity {

ListView lvfid;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //some code
    showFid();
}

private void showFiD(){
    final ArrayList <HashMap<String,String>> al = new ArrayList<HashMap<String,String>>();
    final Dialog dialog = new Dialog(MainActivity.this , R.style.DialogTheme);
    dialog.setContentView(R.layout.field_dialog);
    dialog.setCancelable(true);
    dialog.show();
    Button addField = (Button) dialog.findViewById(R.id.btnfidField);
    lvfid = (ListView) dialog.findViewById(R.id.lvfid);
    addField.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            HashMap<String,String> h = new HashMap<String,String>();
            h.put("name", "");
            h.put("value", "");
            al.add(h);
            lvfid.setAdapter(new FieldAdapter(dialog.getContext(), al));

        }
    });
}

public class FieldAdapter extends BaseAdapter{

private ArrayList <HashMap <String,String>> arrayList;
private LayoutInflater inflater;

public FieldAdapter(Context context, ArrayList<HashMap <String,String>> arrayList) {
    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.arrayList = arrayList;
}

@Override
public int getCount() {
    return arrayList.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int position) {
    return position;
}


@Override
public View getView(int position, View convertView, ViewGroup arg2) {
    View view = null;
    if (convertView == null)
        view = inflater.inflate(R.layout.field_inflater, null);
     else 
        view = convertView;
    Holder holder = new Holder();
    holder.edName     = (EditText) view.findViewById(R.id.edfidName);
    holder.edValue     = (EditText) view.findViewById(R.id.edfidValue);
    //holder.edName.setText(arrayList.get(position).get("name"));
    //holder.edValue.setText(arrayList.get(position).get("value"));
    return view;
}

private class Holder {
    private EditText edName;
    private EditText edValue;
}


}

}

Save a spark RDD using mapPartition with iterator

I have some intermediate data that I need to be stored in HDFS and local as well. I'm using Spark 1.6. In HDFS as intermediate form I'm getting data in /output/testDummy/part-00000 and /output/testDummy/part-00001. I want to save these partitions in local using Java/Scala so that I could save them as /users/home/indexes/index.nt(by merging both in local) or /users/home/indexes/index-0000.nt and /home/indexes/index-0001.nt separately.

Here is my code: Note: testDummy is same as test, output is with two partitions. I want to store them separately or combined but local with index.nt file. I prefer to store separately in two data-nodes. I'm using cluster and submit spark job on YARN. I also added some comments, how many times and what data I'm getting. How could I do? Any help is appreciated.

 val testDummy = outputFlatMapTuples.coalesce(Constants.INITIAL_PARTITIONS).saveAsTextFile(outputFilePathForHDFS+"/testDummy")
 println("testDummy done")   //1 time print

def savesData(iterator: Iterator[(String)]): Iterator[(String)] = {
    println("Inside savesData")                                 //  now 4 times when coalesce(Constants.INITIAL_PARTITIONS)=2
    println("iter size"+iterator.size)                           //  2 735 2 735 values
    val filenamesWithExtension = outputPath + "/index.nt"
    println("filenamesWithExtension "+filenamesWithExtension.length)   //4 times
    var list = List[(String)]()

    val fileWritter = new FileWriter(filenamesWithExtension,true)
    val bufferWritter = new BufferedWriter(fileWritter)

     while (iterator.hasNext){                       //iterator.hasNext is false
       println("inside iterator")                    //0 times 
       val dat = iterator.next()
       println("datadata "+iterator.next())

       bufferWritter.write(dat + "n")
       bufferWritter.flush()
       println("index files written")

       val dataElements = dat.split(" ")
       println("dataElements")                                    //0
       list = list.::(dataElements(0))
       list = list.::(dataElements(1))
       list = list.::(dataElements(2))
     }
    bufferWritter.close() //closing
    println("savesData method end")                         //4 times when coal=2
    list.iterator
}

println("before saving data into local")                              //1
val test = outputFlatMapTuples.coalesce(Constants.INITIAL_PARTITIONS).mapPartitions(savesData)
println("testRDD partitions "+test.getNumPartitions)                               //2
println("testRDD size "+test.collect().length)                                //0
println("after saving data into local")   //1

PS: I followed, this and this but not exactly same what I'm looking for, I did somehow but not getting anything in index.nt

ADB Install seems to fail (preventing me from debugging on device using Visual Studio)

I use VS2015 with Xamarin to deploy an app to my phone. After recently rooting and wiping my phone data, I'm receiving errors upon deploying. The most common issue was that the "Fast deploy" was enabled, but I already had that turned off.

I figured out that my ADB Install seems to fail (permission denied), giving me the following error:

failed to copy 'x' to '/data/local/tmp/x': Permission denied

It really starts working on my nerves, and after trying several things which I found on the internet, I ended up asking a question here.

When I go to my 'ADB Shell' (running in root mode and showing this # sign), and type 'ls -ld data data/local data/local/tmp'

it shows the following, which seems to be normal (according to things I read): drwxrwx--x system system 2016-06-26 15:11 data drwxr-x--x root root 2016-06-26 08:52 local drwxrwx--x shell shell 2016-06-26 01:58 tmp

I started by recreating the 'tmp' folder, and using 'EF File Explorer' on my phone I can modify things and do everything I'd like to do. (modify rights, add folders, remove folders, recreate the folders and so on).

When I go to 'Root explorer' in EF File Explorer, I changed the '/' folder mode to 'RW', but it didn't make any change. Root explorer says it's still on "r/o" (read only) mode.

I tried the 'busybox mount -o remount, rw /system' trick and other mount-commands which did the trick for others, but still same issue with my phone. Furthermore, I tried a "move" trick in the shell, which didn't work out either.

As a last option I even tried to do a full format/wipe, but even thát did not solve my issue.

So I'm currently back at square one, where my 'ls -ld' is still showing the same information. Copying files to the internal storage via Windows Explorer works as it should.

Hopefully I'm doing something stupid and is there a fix for this issue. Thanks in advance for your help.

Android - Jacoco code coverage ignores Robolectric tests

Trying to get Code coverage on my Robolectric tests in Android utilising Jacoco but it simply refuses to acknowledge my Robolectric tests when creating the reports.

My jacoco.gradle file is as follows:

apply plugin: 'jacoco'

jacoco {
    toolVersion = "0.7.6.201602180812"
}

project.afterEvaluate {

    android.applicationVariants.all { variant ->
        def name = variant.name
        def testTaskName = "test${name.capitalize()}UnitTest"

        tasks.create(name: "${testTaskName}Coverage", type: JacocoReport, dependsOn: "$testTaskName") {
            group = "Reporting"
            description = "Generate Jacoco coverage reports for the ${name.capitalize()} build."

            classDirectories = fileTree(
                    dir: "${project.buildDir}/intermediates/classes/${name}",
                    excludes: ['**/R.class',
                               '**/R$*.class',
                               '**/*$ViewInjector*.*',
                               '**/*$ViewBinder*.*',
                               '**/BuildConfig.*',
                               '**/Manifest*.*']
            )

            sourceDirectories = files(['src/main/java'].plus(android.sourceSets[name].java.srcDirs))
            executionData = files("${project.buildDir}/jacoco/${testTaskName}.exec")

            reports {
                xml.enabled = true
                html.enabled = true
            }
        }
    }
}

With this setup I can get Coverage reports but I get 0% coverage despite having Robolectric tests in "src/test/java".

If I add in the following code to that file:

android {
    testOptions {
        unitTests.all {
            jacoco {
                includeNoLocationClasses = true
            }
        }
    }
}

I get the following error when Gradle tries to sync:

Error:No such property: includeNoLocationClasses for class: org.gradle.testing.jacoco.plugins.JacocoTaskExtension_Decorated

I know that I need to have Gradle 2.13 to use this includeNoLocationClasses value so in graddle-wrapper.properties I have the following:

#Wed Apr 10 15:27:10 PDT 2013
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https://services.gradle.org/distributions-snapshots/gradle-2.13-20160228000026+0000-all.zip

I am pretty certain I am running Gradle 2.13 with Android plugin version 1.5

In my apps Gradle file I have the following:

//...

apply from: 'jacoco.gradle'

//..

testOptions {
    unitTests.returnDefaultValues = true
}

//...

debug {
    testCoverageEnabled true
}

And the command I use to run the coverage is:

./gradlew createDebugCoverageReport

So I am wondering why I get the includeNoLocationClasses error despite using the correct Gradle version? And outside of that maybe I am doing something wrong where Jacoco isn't picking up the Robolectric tests in src/test.java ?

RxAndroid: Observable.first() returns List of null objects

Following this tutorial I've created two sources for fetching data. I expect that if there is no data locally I'll sent network request. But all the time get list of null objects from local source (which is first in Observable.concat).

For local source using SQLite with SQLBrite wrapper and Retrofit for remote source:

@Override
public Observable<Item> get(String id) {
    //creating sql query

    return databaseHelper.createQuery(ItemEntry.TABLE_NAME, sqlQuery, id)
        .mapToOneOrDefault(mapperFunction, null);
}

There is method in repository for concating observables:

@Override
public Observable<Item> get(String id) {
    Observable<Item> local = localDataSource
        .get(id)
        .doOnNext(new Action1<Item>() {
            @Override
            public void call(final Item item) {
                // put item to cache
            }
        });
    Observable<Item> remote = remoteDataSource
        .get(id)
        .doOnNext(new Action1<Item>() {
            @Override
            public void call(final Item item) {
                // save item to database and put to cache
            }
        });
    return Observable.concat(local, remote).first();
}

For getting it with list of ids I'm using next method:

@Override
public Observable<List<Item>> getList(final List<String> ids) {
    return Observable
        .from(ids)
        .flatMap(new Func1<String, Observable<Item>>() {
            @Override
            public Observable<Item> call(String id) {
                return get(id);
            }
        }).toList();
}

And subscription in fragment:

Subscription subscription = repository
    .getList(ids)
    .flatMap(new Func1<List<Item>, Observable<Item>>() {
        @Override
        public Observable<Item> call(List<Item> result) {
            return Observable.from(result);
        }
    })
    .toList()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(new Observer<List<Item>>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onNext(List<Item> result) {
            // there get list of null objects
        }
}); 

So, main goal is first check local storage and if there is no item - make request to server. But now if item isn't exist I get null instead of send request.

Could someone help me understand why?

Using Threads to sum numbers from a vector

I dont think im understand Threads as i should be. Im trying to make a very redundant app in android that gets user input(Numbers) and stores them inside a vector. From that vector i start 7 Threads that should sum up all the numbers from that vector in whatever random order and when its done should Log the output. But what im getting is 7 Threads each summing up everything by itself... So im probably not using wait() and notifyAll() correctly.

I have 2 classes that extends Thread:

MasterThread:

 public MasterThread(int M,String nums){
    SumArray = new SumThread[M];
    SumVector = new Vector<>();
    SumString(nums);
}

@Override
public synchronized void run(){
    for (int i = 0; i <7 ; i++) {
        SumArray[i] = new SumThread(this);
        SumArray[i].start();
    }
}

From what i understand each Thread get its own 'this' and so every Thread gets its own vector, but i did make SumVector a static variable so i hoped it would use that one only.

The more important class is the SumThread:

public void run(){
    first = getRandom(m.SumVector);
    second = getRandom(m.SumVector);
    sumit(first, second);
    m.SumVector.add(first+second);
    while (m.SumVector.size() > 1) {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    Log.d("Output:", m.SumVector.toString());
}

private synchronized void sumit(int f, int s){
    m.SumVector.removeElement(f);
    m.SumVector.removeElement(s);
    notifyAll();
}

Which is where im probabaly doing something wrong.

I thought that each SumThread gets the same Vector from MasterThread, so i get two random numbers from the vector and then i remove them from the vector and add back the value of them both, and while i have more than one number, continue doing it. So by theory whatever thread gets there first takes two numbers,that wont be in the vector again, while other threads get other numbers or sum them.

But well the output i get is:

D/Output:: [24]
D/Output:: [48]
D/Output:: [96]
D/Output:: [192]
D/Output:: [384]
D/Output:: [768]
D/Output:: [1536]

Sorry for always asking lengthy questions haha Any help/advice is appreciated.

Thanks, -Kan-

Java: Format elements and count number of reoccurring elements in a 2d array

I'm trying to determine how many times each number between 0-999 has been used in the array. Also I'm wanting to format the elements so that its always a 3 digit number. instead of '21' it would be '021', '5' would be '005'. Netbeans is saying to use an enhanced loop in place of for(int x=0;x

public static void main(String[] args) {
    //Creator of random number 0-999
    Random creator = new Random(999);

    int lotto[][] = new int[1000][2];
    int count = 0;

    for(int x=0;x<lotto.length; x++){
        for(int y = 0; y < lotto[x].length; y++){
            //Fills element with random number
            lotto[x][y] = creator.nextInt(999);
        }
    }
    //Place holder to print out array
    for(int[] a: lotto){
        System.out.println(Arrays.toString(a));
    }
}

}

Edit: I've tried this

for(int x=0;x<lotto.length; x++){
        for(int y = 0; y < lotto[x].length; y++){
            //Fills element with random number
            ++lotto[creator.nextInt(999)][creator.nextInt(999)];
        }
    }
 for(int j=0; j < lotto.length;j++){
        System.out.println(j +""+ lotto[j]);
 }

But now the program doesnt run. I think the ++lotto is right to count how many time that element is used.

Edit 2:

 List<Integer> list = new ArrayList<>();
    for(int x=0;x<lotto.length;x++){
        for(int y=0; y<lotto[x].length; y++){
            list.add(lotto[x][y]);
        }
    }
    for(int x=0; x<1000; x++){
        if(list.contains(x)){
            int index = 0;
            int countList = 0;
            while(index!= -1){
                countList++;
                list.remove(index);
                index = list.indexOf(x);
            }
            System.out.println(x +" Hit "+ countList + "time(s)");
        }
    }

When the array prints out, theres 1 less the number of found elements in the array as what the list is printing out.

UPDATE: For some reason now the source below to count the list, the number doesnt match the count of the number of times the user's input is. ie: user inputs 200, it counts 200 was used twice but the list only prints out it was found once

for(int x=0;x<lotto.length;x++){
        for(int y = 0; y < lotto[x].length; y++){
            if(lotto[x][y]== lottery)
                count++;
        }
    }

android service run multiple

this is my service code

public class MyCustomService extends Service {
public static final String INPUT_TEXT="INPUT_TEXT";
public static final String OUTPUT_TEXT="OUTPUT_TEXT";
private volatile HandlerThread mHandlerThread;
private ServiceHandler mServiceHandler;
public Socket client;

// ...


// Define how the handler will process messages
private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    // Define how to handle any incoming messages here
    @Override
    public void handleMessage(Message message) {
        // ...
        // When needed, stop the service with
        // stopSelf();
    }
}


// Fires when a service is first initialized
public void onCreate() {
    super.onCreate();
    // An Android handler thread internally operates on a looper.
    mHandlerThread = new HandlerThread("MyCustomService.HandlerThread");
    mHandlerThread.start();
    // An Android service handler is a handler running on a specific background thread.
    mServiceHandler = new ServiceHandler(mHandlerThread.getLooper());



}


// Fires when a service is started up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Send empty message to background thread
    mServiceHandler.sendEmptyMessageDelayed(0, 500);
    // or run code in background
    mServiceHandler.post(new Runnable() {
        @Override
        public void run() {
            // Do something here in background!

            IO.Options opts = new IO.Options();
            opts.query = "auth_token=51";
            try {
                client = IO.socket("http://192.168.0.106:3000/",opts);
                client.on("message", onMessage);
                client.connect();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }


            // If desired, stop the service
            //stopSelf();
        }
    });
    // Keep service around "sticky"
    return START_STICKY;
}

// ...

// Defines the shutdown sequence
@Override
public void onDestroy() {
    // Cleanup service before destruction
    client.disconnect();
    client.close();
    mHandlerThread.quit();
}


private Emitter.Listener onMessage = new Emitter.Listener() {
    @Override
    public void call(Object... args) {
        String message = (String) args[0];
        Log.d("recive message message message", message);

        /*create new intent to broadcast our processed data to our activity*/
        Intent resultBroadCastIntent = new Intent();
        /*set action here*/
        //resultBroadCastIntent.setAction(TextCapitalizeResultReceiver.ACTION_TEXT_CAPITALIZED);
        resultBroadCastIntent.setAction(Intent.ACTION_SEND);
        /*set intent category as default*/
        // resultBroadCastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        /*add data to intent*/
        resultBroadCastIntent.putExtra(OUTPUT_TEXT, message);
        /*send broadcast */
        sendBroadcast(resultBroadCastIntent);

    }
};


@Override
public IBinder onBind(Intent intent) {
    return null;
}
}

and i run it from activity this code in onCreate

    Intent i = new Intent(this, MyCustomService.class);

    i.putExtra("foo", "bar");

    startService(i);

problem to me its every time i enter main Activity and its run service twice or 3 or 4 times so when i receive new message by socket its received same message three or Four times

Can not call class android

I have code using onClickListener, I'm trying to call class NetCheck but error like this http://prntscr.com/blgi94. When I try put the class NetCheck in outside onClickListener get error in this line http://prntscr.com/blginf. I don't know how to fix it. Anyone can help me?

My code

premi.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            // get prompts.xml view
            LayoutInflater li = LayoutInflater.from(context);
            View promptsView = li.inflate(R.layout.update, null);
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    context);
            // set prompts.xml to alertdialog builder
            alertDialogBuilder.setView(promptsView);
            final EditText userInput = (EditText) promptsView
                    .findViewById(R.id.editTextDialogUserInput);
            userInput.setText(cash.getText());
            // set dialog message
            alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,int id) {
                                    // get user input and set it to result
                                    // edit text
                                    //result.setText(userInput.getText());
                                    class NetCheck extends AsyncTask<String, String, String> {

                                        /**
                                         * Before starting background thread Show Progress Dialog
                                         * */
                                        @Override
                                        protected void onPreExecute() {
                                            super.onPreExecute();
                                            pDialog = new ProgressDialog(IGNActivity.this);
                                            pDialog.setMessage("Creating ID Game Master..");
                                            pDialog.setIndeterminate(false);
                                            pDialog.setCancelable(true);
                                            pDialog.show();
                                        }

                                        /**
                                         * Creating product
                                         * */
                                        protected String doInBackground(String... args) {
                                            String ign = editTextId.getText().toString().trim();
                                            String cash = userInput.getText().toString();

                                            // Building Parameters
                                            List<NameValuePair> params = new ArrayList<NameValuePair>();
                                            params.add(new BasicNameValuePair("ign", ign));
                                            params.add(new BasicNameValuePair("cash", cash));

                                            // getting JSON Object
                                            // Note that create product url accepts POST method
                                            JSONObject json = jsonParser.makeHttpRequest(url_input_item,
                                                    "POST", params);

                                            // check log cat fro response
                                            Log.d("Create Response", json.toString());

                                            // check for success tag
                                            try {
                                                int success = json.getInt(TAG_SUCCESS);

                                                if (success == 1) {
                                                    // successfully created product
                                                    //Toast.makeText(CreateIDGM.this, "Success Create ID Game Master ", Toast.LENGTH_SHORT).show();


                                                    // closing this screen
                                                    finish();
                                                } else {
                                                    // failed to create product
                                                }
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                        protected void onPostExecute(String file_url) {
                                            // dismiss the dialog once done
                                            pDialog.dismiss();
                                            Intent i = new Intent(getApplicationContext(), IGNActivity.class);
                                            startActivity(i);
                                            Toast.makeText(IGNActivity.this, "Success Input Item ", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,int id) {
                                    dialog.cancel();
                                }
                            });


            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();
            // show it
            alertDialog.show();
        }
    });

Align two textviews so that the right one resizes until max and the left one fits in

I need a table-like view in Android which I can fill with custom name-value rows. A row consists of two horizontally-placed text views which hold the name and the value. Every row should have the following properties:

  • The left text view is aligned to parent-left, and the right one is aligned to parent-right.
  • The right text never becomes longer than 7 ems, but can be smaller.
  • The left text should fill up the remaining space in the row.
  • Obviously, the two text views should never overlap.

Currently I'm trying to solve this with a LinearLayout as the container and two TextViews wrapped in a RelativeLayout, but something's clearly out of place here (the underlined bit is clearly longer than 7 ems):

enter image description here


My XMLs:

The row layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dp"
    android:paddingTop="4dp">

    <TextView
        android:id="@+id/tb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:ellipsize="end"
        android:maxEms="7"
        android:maxLines="2" />

    <TextView
        android:id="@+id/tb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:ellipsize="end"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_centerVertical="true"
        android:layout_toLeftOf="@id/tb2"
        android:layout_toStartOf="@id/tb2" />
</RelativeLayout>

The container layout into which the rows are added programatically:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:padding="16dp"/>

I'm using this layout as part of a dialog. Not sure if it adds anything to the problem or not.

Any ideas/solutions?

Async error occured while executing doInBackground()

Stacktrace:

06-26 15:30:45.019 2960-2996/yonitheweatherapp.theweatherapp E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                                                                           Process: yonitheweatherapp.theweatherapp, PID: 2960
                                                                           java.lang.RuntimeException: An error occurred while executing doInBackground()
                                                                               at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                               at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                               at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                               at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                               at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                               at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                               at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                               at java.lang.Thread.run(Thread.java:818)
                                                                            Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
                                                                               at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
                                                                               at org.json.JSONTokener.nextValue(JSONTokener.java:94)
                                                                               at org.json.JSONObject.<init>(JSONObject.java:156)
                                                                               at org.json.JSONObject.<init>(JSONObject.java:173)
                                                                               at data.JSONWeatherParser.getWeather(JSONWeatherParser.java:22)
                                                                               at yonitheweatherapp.theweatherapp.MainActivity$WeatherTask.doInBackground(MainActivity.java:66)
                                                                               at yonitheweatherapp.theweatherapp.MainActivity$WeatherTask.doInBackground(MainActivity.java:60)
                                                                               at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                               at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                               at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
                                                                               at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
                                                                               at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
                                                                               at java.lang.Thread.run(Thread.java:818) 

06-26 15:30:45.780 2960-2999/yonitheweatherapp.theweatherapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae4513f0

doInBackground():

    private class WeatherTask extends AsyncTask<String, Void, Weather>{
    @Override
    protected Weather doInBackground(String... params) {

        String data = ((new WeatherHttpClient()).getWeatherData(params[0]));

        weather = JSONWeatherParser.getWeather(data);

        return weather;
    }

    @Override
    protected void onPostExecute(Weather weather) {
        super.onPostExecute(weather);
    }

WeatherHttpClient(): public class WeatherHttpClient {

public String getWeatherData(String place){
    HttpURLConnection connection = null;
    InputStream inputStream = null;

    try {
        connection = (HttpURLConnection) (new URL(Utils.BASE_URL + place)).openConnection();
        connection.setRequestMethod("GET");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        //read the response
        StringBuffer stringBuffer = new StringBuffer();
        inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;

        while((line = bufferedReader.readLine()) != null){
            stringBuffer.append(line + "rn");
        }



        inputStream.close();
        connection.disconnect();

        return stringBuffer.toString();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

}

Any help please? I couldnt find the correct solution by myself.