jeudi 13 août 2015

Can someone help me with aidl while using android:process?

I wrote an aidl service and set android:process=".remote" in AndroidManifest, but I can only get the original data and while the data updated, the data I get doesn't change. But while I delete the android:process it works. Why did this happen and how does android:process works?

for example: aidl:

interface ILoginInfoService {
    String getLoginInfo();
}

TestService:

public class TestService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
    private final ILoginInfoService.Stub mBinder = new ILoginInfoService.Stub() {
        @Override
        public String getLoginInfo() throws RemoteException {
            return TestClass.string;
        }
    };
}

TestClass:

public class TestClass {
    static String string = "a";
}

TestActivity:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        TestClass.string += "a";
        try {
            if(mRemoteService.getLoginInfo() != null) {
                textView.setText(mRemoteService.getLoginInfo());
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
});

it only shows "a" while i click the button, but if i delete the android:process below ,the string will increase("a", "aa", "aaa", ...).

<service android:name=".TestService" android:process=".remote">
    <intent-filter>
        <action android:name="com.example.chayne_shen.testservice.TestService" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>



via Chebli Mohamed

Android transparent status bar implementation?

I noticed Play Store application detail pages show a transparent status bar since version 5.4, but how is it implemented?

I tried to add WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS flag to my window, but the result is both the status bar and the navigation bar are transparent. How can I just make the status bar transparent but the navigation bar keeps normal?



via Chebli Mohamed

AsyncTask that can show progress when synchronous, execute().get()

Another Android puzzler. Sure someone has an answer, but I can't figure it out. Here's the scenario and then I will show some code...

I have a list of data (call them "Forms") I want to submit to our servers. Each of these "Forms" can have media associated with them, the task is syncPendingFormsResultTask. On top of that, sometimes as I am submitting the "Form" I may have to prompt the user for more information before submitting it. That prompting requires me to get more info, right at that moment, from the server...another AsyncTask call, workflowTask.

My problem is showing progress and also gathering the data. The tendency is for the Dialogs prompting for more data to display last and for no progress dialog information to be shown. It works fine for a single instance, so I know it must be AsyncTask related (not the first time there!).

The logic is something like this:

Loop forms

 if (more data)
     AsyncTask get more data (synchronous using .get())
     Dialog to prompt user with data from AsyncTask 
         AsyncTask to submit gathered data, show progress progress of media
             being sent to server
 else 
     AsyncTask to submit gathered data, show progress of media being sent to
             server

Please note that in the onClick in the promptUserForWorkflowInfo the same AsyncTask syncPendingFormsResultTask to submit data is called. I have tried to make the syncPendingFormsResultTask synchronous (using execute().get()) without success.

Bottom line is that I would like this all to really be synchronous and to display the progress...for example with 3 "Forms" and 1 needing extra data it would:

Form 1 (no data needed)...sending 1 of 3 media
Form 1 (no data needed)...sending 2 of 3 media
Form 1 (no data needed)...sending 3 of 3 media
Form 2 - Getting extra data from server...
Form 2 - Prompt user for more data
Form 2 (extra data)    ...sending 1 of 3 media
Form 2 (extra data)...sending 2 of 3 media
Form 2 (extra data)...sending 3 of 3 media
Form 3 (no data needed)...sending 1 of 3 media
Form 3 (no data needed)...sending 2 of 3 media
Form 3 (no data needed)...sending 3 of 3 media

Everything does seem to submit fine, just not getting progress or prompting for data in order shown.

Code:

         Integer cnt = 1;
         Integer size = pendingForms.size();
         for (FormSimple pendingForm : pendingForms) {

             Form form = libraryUtils.retrieveFormInstanceForm(pendingForm.getInstanceId());

             if (form.getWorkflow() != null) {
                 // before we submit, check to see if we need to get workflow info
                 ArrayList<WorkflowInfo> workflowinfo = null;
                 try {
                     workflowinfo = new workflowTask().execute(form).get();
                     promptUserForWorkflowInfo(getActivity(), form, workflowinfo, size, cnt);
                 }
                 catch (Exception ex) {
                     Utilities.logException(ex);
                 }
             }
             // Just submit
             else {
                 new syncPendingFormsResultTask().execute(form, size, cnt); 
             }

             // Increment count
             cnt++;
         }                   

Finally, I have also tried to



via Chebli Mohamed

How to layout a RelativeLayout in a custom view's onLayout function?

I am implementing a custom view, and I have three subviews that I can't get to appear. It seems like the subviews aren't showing; I have set the backgrounds to be red, blue, and green for now to show where I have made set the layout, which is shown in the picture.

I need the subviews to be shown so that the view is complete.

This is the code I'm using in onLayout for the subviews:

    backButton.layout(leftOffset, topOffset, leftOffset + seventhWidth, topOffset + seventhWidth);
    backButton.setBackgroundColor(Color.RED);
    nextButton.layout((int) (leftOffset + calendarWidth - seventhWidth), topOffset, (int) (leftOffset + calendarWidth), topOffset + seventhWidth);
    nextButton.setBackgroundColor(Color.GREEN);
    monthContainerLayout.layout(leftOffset + thirdWidth, topOffset, (int) Math.round(leftOffset + 2 * thirdWidth), topOffset + seventhWidth);
    monthContainerLayout.setBackgroundColor(Color.BLUE);

This is the layout XML for the red square:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:id="@+id/back"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:src="@drawable/back_icon"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/icon_height" />

</RelativeLayout>

This is what the code and layout currently produces (my custom view is only the calendar):

enter image description here



via Chebli Mohamed

How to get app's metadata from another app?

I am trying to add a feature to my app which receives broadcast data from Spotify and does something with that data. However, I am not sure how to proceed. I've been able to piece together the following code with the help of previous questions, however those questions do not go into detail on how to actually initiate the reception of data. I have a BroadCast Receiver:

<receiver
        android:name=".Receiver"
        android:enabled="true"
        android:exported="true">

        <intent-filter>
            <action android:name="com.spotify.music.playbackstatechanged"/>
            <action android:name="com.spotify.music.metadatachanged"/>
            <action android:name="com.spotify.music.queuechanged"/>
        </intent-filter>

    </receiver>

I have a BroadCast Receiver class (all set up):

public class Receiver extends BroadcastReceiver {

static final class BroadcastTypes {
    static final String SPOTIFY_PACKAGE = "com.spotify.music";
    static final String PLAYBACK_STATE_CHANGED = SPOTIFY_PACKAGE + ".playbackstatechanged";
    static final String METADATA_CHANGED = SPOTIFY_PACKAGE + ".metadatachanged";
}


@Override
public void onReceive(Context context, Intent intent) {

    long timeSentInMs = intent.getLongExtra("timeSent", 0L);
    String action = intent.getAction();

    if (action.equals(BroadcastTypes.METADATA_CHANGED)) {

        String trackId = intent.getStringExtra("id");
        String artistName = intent.getStringExtra("artist");
        String albumName = intent.getStringExtra("album");
        String trackName = intent.getStringExtra("track");
        int trackLengthInSec = intent.getIntExtra("length", 0);

        //send data to main class?

    } else if (action.equals(BroadcastTypes.PLAYBACK_STATE_CHANGED)) {

        boolean playing = intent.getBooleanExtra("playing", false);
        int positionInMs = intent.getIntExtra("playbackPosition", 0);

        //send data to main class?
    }

  }
}

and I have a main Activity class. So now I am not sure how I can actually start the acquisition of data from Spotify in my main activity, or how to then send that data (from the receiver) back to my main activity for later use.

Thanks for any advice



via Chebli Mohamed

POST String From Android To Php

I'm having trouble posting a String from android to php. I'm trying to post a username since I was to exclude the current users username from the query. In Java I have an AsyncTask with the code below in the doInBackground(String... params)

ArrayList<NameValuePair> data_to_send = new ArrayList<>();
    data_to_send.add(new BasicNameValuePair("Username", username));

    HttpParams httpRequestParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpRequestParams, ServerRequests.CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpRequestParams, ServerRequests.CONNECTION_TIMEOUT);


    HttpClient client = new DefaultHttpClient(httpRequestParams);
    HttpPost post = new HttpPost(ServerRequests.SERVER_ADDRESS + "TestQuery.php");

    try {
        post.setEntity(new UrlEncodedFormEntity(data_to_send));
        client.execute(post);
    } catch (Exception e) {

        e.printStackTrace();
    }

And this is in my php:

$origLat = 45.6215349;
$origLon = 18.6951613;
$dist = 30; 
$username = $_POST["Username"];

$sql = "SELECT ID, Username, Name, Age, City, Gender, Latitude, Longitude, 3956 * 2 * 1.609344 * 1000 *
      ASIN(SQRT( POWER(SIN(($origLat - abs(Latitude))*pi()/180/2),2)
      +COS($origLat*pi()/180 )*COS(abs(Latitude)*pi()/180)
      *POWER(SIN(($origLon-Longitude)*pi()/180/2),2))) 
      as distance FROM users WHERE Username != '$username'
      AND Longitude BETWEEN ($origLon-$dist/abs(cos(radians($origLat))*69)) 
      AND ($origLon+$dist/abs(cos(radians($origLat))*69)) 
      AND Latitude BETWEEN ($origLat-($dist/69)) 
      AND ($origLat+($dist/69))
      HAVING distance < $dist ORDER BY distance limit 30;"; 

Well the query works when I input the String directly by changing the Username != 'Jawe' but I'm not sure why it doesn't work when posted from Android. Anyone know the problem?



via Chebli Mohamed

Accessing model data from fragments of viewpager

I'm currently writing an app that displays cooking recipes when clicked.

My data is stored in a custom content provider and the information for my recipes is stored in 3-4 tables.

DetailActivity contains a Fragment(Let's call is MasterFragment).

MasterFragment contains a ViewPager which holds 3 fragments that display the main parts of my model: general info, ingredients and directions. Let's call them GeneralFragment, IngredientFragment and DirectionFragment.

How it stands now, the 3 fragments of the ViewPager all receive the appropriate Uri and each has a loader that loads the data from the content provider and displays it in my UI.

My problem is that having the data loaded into the 3 fragments adds a lot of complexity to my code when it comes to updating the data in the content provider. On top of that, I feel like that doing in this manner may not be the most efficient way of fetching and displaying my data.

One alternative that I thought of was to query all the data in my MasterFragment and to pass it to each individual fragment of the ViewPager through the its adapter. Once again, this is a hassle that requires a lot of overhead and may not be optimal.

I'm thinking that the best way of doing it may be to centralize the model data into the MasterFragment and have the fragments access that data. I'm just not sure how to implement this. I'm leaning towards using a singleton recipe class but I'd rather here your opinion before implementing it.

I'd appreciate any input and I thank you in advance for your time.

tl;dr: Model needs to be accessed by 3 fragments in a viewpager, what is the best way of doing this?



via Chebli Mohamed

RxJava Can't create handler inside thread that has not called Looper.prepare()

Okay, so I am having a bit of trouble with an RxJava Observable I am using in my Android app. It is extremely frustrating because this has been working for a while now and is only now throwing the error above. I am aware that this means I am doing a UI operation from another thread but I do not see where that is happening. So here is the observable:

 ConnectionsList.getInstance(this).getConnectionsFromParse(mCurrentUser)
            .delay(3, TimeUnit.SECONDS)
            .flatMap(s -> mainData.getDataFromNetwork(this, mCurrentUser, mSimpleFacebook))
            .flatMap(s -> mainData.getPictureFromUrl(s))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Bitmap>() {
                @Override
                public void onCompleted() {
                    if (mCurrentUser.get(Constants.NAME) != null) {
                        mNavNameField.setText((String) mCurrentUser.get(Constants.NAME));
                    }
                    mSearchFragment.setupActivity();
                }

                @Override
                public void onError(Throwable e) {
                    e.printStackTrace();
                    mSearchFragment.setEmptyView();
                }

                @Override
                public void onNext(Bitmap bitmap) {
                    mNavProfImageField.setImageBitmap(bitmap);
                    mainData.saveImageToParse(bitmap); //save the image to Parse backend
                }
            });

After some debugging I found that this flatmap is where the error is happening:

.flatMap(s -> mainData.getDataFromNetwork(this, mCurrentUser, mSimpleFacebook))

Inside of that is the following, I have added a comment where the error is being thrown:

 return Observable.create(subscriber -> {
            //set the username field if ParseUser is not null
            if(currentUser != null) {
                username = (String) currentUser.get(Constants.NAME);
            }

            //if prof pic is null then request from facebook. Should only be on the first login
            if (currentUser != null && currentUser.getParseFile(Constants.PROFILE_IMAGE) == null) {
                if (AccessToken.getCurrentAccessToken() != null) { //check if session opened properly
                    //get simple facebook and add the user properties we are looking to retrieve
                    Profile.Properties properties = new Profile.Properties.Builder()
                            .add(Profile.Properties.FIRST_NAME)
                            .add(Profile.Properties.GENDER)
                            .add(Profile.Properties.BIRTHDAY)
                            .add(Profile.Properties.ID)
                            .add(Profile.Properties.EMAIL)
                            .build();

                    //The following line is where the debugger stops 
                    //and the error gets thrown
                    simpleFacebook.getProfile(properties, new OnProfileListener() {
                        @Override
                        public void onComplete(Profile response) {
                            String id = response.getId();
                            String name = response.getFirstName();
                            String gender = response.getGender();
                            String birthday = response.getBirthday();
                            String email = response.getEmail();
                            String age = getAge(birthday);

                            currentUser.put(Constants.NAME, name);
                            currentUser.put(Constants.AGE, age);
                            currentUser.put(Constants.GENDER, gender);
                            currentUser.put(Constants.EMAIL, email);
                            currentUser.saveInBackground();

                            if (id != null) { //display the profile image from facebook
                                subscriber.onNext("http://ift.tt/wljqS4" + id + "/picture?type=large");
                            }
                        }

Whats going on here? Its been working fine as is and now it is saying that I am on some helper thread. As far as I was concerned I was on the UI thread up to this point. If someone can help me that would be great, otherwise I may have to drop RxJava for the time being as it is not working out for me. Thanks in advance!



via Chebli Mohamed

Opencv android app keeps crashing

I am trying to create a color recognition app for android. I want to check if a color is in range and measure the time it takes for that color to be in range. My problem is my app quits unexpectedly when it hit the "start test" button. I have no idea why its doing this, I believe I have set everything up right, but obviously I'm incorrect.

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;


public class testActivity extends AppCompatActivity implements CameraBridgeViewBase.CvCameraViewListener2 {

private JavaCameraView mOpenCVCameraView;
Mat videoCamera;
Mat whiteArray;

private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
    @Override
    public void onManagerConnected(int status){
        switch (status){
            case LoaderCallbackInterface.SUCCESS: {
                mOpenCVCameraView.enableView();
                break;
            }
            default:{
                super.onManagerConnected(status);
            }
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    mOpenCVCameraView = (JavaCameraView) findViewById(R.id.testPageBackground);
    mOpenCVCameraView.setVisibility(SurfaceView.INVISIBLE);
    mOpenCVCameraView.setCvCameraViewListener(this);
    getSupportActionBar().hide();
}

@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_test, menu);
    mOpenCVCameraView.setCvCameraViewListener(this);
    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);
}
public void onResume() {
    super.onResume();
    OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_9, this, mLoaderCallback);
}

public void onDestroy(){
    super.onDestroy();
    if (mOpenCVCameraView != null){
        mOpenCVCameraView.disableView();
    }
}

@Override
public void onCameraViewStarted(int width, int height) {
    videoCamera = new Mat(5,5,CvType.CV_8SC4);
    whiteArray = new Mat(5,5,CvType.CV_8SC4);
}

@Override
public void onCameraViewStopped() {
    videoCamera.release();
    whiteArray.release();
}

@Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame)
{

    return inputFrame.rgba();
}

public void startTest (View view)
{
    View lagSquare = findViewById(R.id.lagSquare);
    TextView lagRating = (TextView) findViewById(R.id.lagRating);
    TextView lagTime = (TextView) findViewById(R.id.lagTime);
    double[] timeArray = new double[100]; // set array
    int testAmount;
    double rating;
    double lagStartTime;
    double lagEndTime;
    double lagTimeResult;
    for (testAmount = 0; testAmount < 100; testAmount++) //test loop
    {
        lagSquare.setBackgroundColor(Color.rgb(000,000,000)); //set lagSquare black
        lagStartTime = System.nanoTime(); //start lagTimer start
        lagSquare.setBackgroundColor(Color.rgb(255, 255, 255)); //set lagSquare white
        //set loop that checks for white
        Core.inRange(videoCamera, new Scalar(0, 0, 95), new Scalar(0, 0, 100), whiteArray);
        while (Core.countNonZero(whiteArray) == 0);
        {
        }
        lagEndTime = System.nanoTime(); //start lagTimer end
        lagTimeResult = (lagEndTime - lagStartTime);//stop lag timer
        timeArray[testAmount] = lagTimeResult; //put lagTimerResult in array


    }
    // min scan
    double minTimeArray = timeArray[0];
    for (int cnt=0; cnt < timeArray.length; cnt++ )
    {
        if (timeArray[cnt] < minTimeArray)
        {
            minTimeArray = timeArray[cnt];
        }
    }
    String minTimeArrayString = String.valueOf(minTimeArray);
    lagTime.setText(minTimeArrayString); //smallest number in timer array output to lagTime label

}

}

08-13 18:41:19.613  25826-25826/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: bluemage.systems.displaylatencytester, PID: 25826
    java.lang.IllegalStateException: Could not execute method of the activity
            at android.view.View$1.onClick(View.java:4020)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4015)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to read from field 'long org.opencv.core.Mat.nativeObj' on a null object reference
            at org.opencv.core.Core.countNonZero(Core.java:2053)
            at bluemage.systems.displaylatencytester.testActivity.startTest(testActivity.java:125)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4015)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)



via Chebli Mohamed

Android Custom Font issue

I am working on a android application. In this application, I am using Custom font (avenir_bold_font). I am using following method to set up font to buttons.

public static void setButtonFont(Activity activity, Button btnView, String fontType){
    Typeface tf = Typeface.createFromAsset(activity.getAssets(),"fonts/"+fontType);
    btnView.setTypeface(tf);
}

Using above method am able to set up font to a button without any trouble. But in above method i have creating Typeface object every time any other calls it.

So i have made the changes in above method, I have converted Typeface local variable to Static variable so that it will improve performance, But The moment i created Typeface object as static , it does not work. it does not able to set up font



via Chebli Mohamed

What's causing styles to don't work with API level 16?

So I applied a custom style to my buttons, it works ok with API level 22, but when I test it with API level 16 all my custom styles are gone. What's happening here?. I am an android beginner so probably it's a common behavior but I couldn't find any answer.

Styles are split into 4 xml's representing button states: Pressed, focused, disabled and enabled. I grouped them in 1 xml called button.xml and applied it in styles.xml

button_pressed.xml (focused, disabled and enabled are similar)

<?xml version="1.0" encoding="utf-8"?>

<shape xmlns:android="http://ift.tt/nIICcg"
android:shape="rectangle">
<gradient
    android:angle="90"
    android:endColor="#004B8D"
    android:startColor="#0865B7" />
<size
    android:height="65dp"
    android:width="65dp"/>
<padding
    android:bottom="5dp"
    android:left="5dp"
    android:right="5dp"
    android:top="5dp" />
<stroke
    android:width="1dp"
    android:color="#FFFFFF" />
<corners android:radius="3dp" />
</shape>

button.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://ift.tt/nIICcg">

<item
    android:state_enabled="false"
    android:drawable="@drawable/button_disabled" />
<item
    android:state_pressed="true"
    android:state_enabled="true"
    android:drawable="@drawable/button_pressed" />
<item
    android:state_focused="true"
    android:state_enabled="true"
    android:drawable="@drawable/button_focused" />
<item
    android:state_enabled="true"
    android:drawable="@drawable/button_enabled" />

</selector>

styles.xml

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name ="android:buttonStyle">@style/button</item>
</style>

<style name="button" parent="@android:style/Widget.Button">
    <item name="android:gravity">center_vertical|center_horizontal</item>
    <item name="android:textColor">#FFFFFFFF</item>
    <item name="android:shadowColor">#000000</item>
    <item name="android:shadowDx">0</item>
    <item name="android:shadowDy">-1</item>
    <item name="android:shadowRadius">0.4</item>
    <item name="android:textSize">20sp</item>
    <item name="android:textStyle">bold</item>
    <item name="android:background">@drawable/button</item>
    <item name="android:focusable">false</item>
    <item name="android:clickable">true</item>
    <item name="android:fontFamily">sans-serif-condensed</item>
</style>



via Chebli Mohamed

Android MapView Multiple Random Markers Removal with Double Tap On Marker

I have question about marker. Looks like after I created next marker, the onDoubleTap method of the marker is no longer available for PREVIOUS markers (NOT the last marker created). Any suggestion on how to fix it where I want to be able to remove it each markers randomly with double tapping on it via onDoubleTap method? What is causing for PREVIOUS markers to no lose track of onDoubleTap method? I have notice is I can double tap anywhere in the map and LAST marker disappears. I want only when doubled tapped ON TOP of that marker it only disappears. Also, when my map rotates markers disappears.

Overlay touchOverlay = new Overlay(this) {
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;

@Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {

}

 @Override
 public boolean onSingleTapConfirmed(final MotionEvent e,
 final MapView mapView) {
 Projection proj = mapView.getProjection();
 GeoPoint loc = (GeoPoint) proj.fromPixels((int) e.getX(),
 (int) e.getY());
 ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
 OverlayItem mapItem = new OverlayItem("", "", new GeoPoint(
 (((double) loc.getLatitudeE6()) / 1000000),
 (((double) loc.getLongitudeE6()) / 1000000)));
 mapItem.setMarker(OfflineMapDemoActivity.this.getResources()
 .getDrawable(R.drawable.location_mark));
 overlayArray.add(mapItem);
 anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(
                        getApplicationContext(), overlayArray, null);
 mapView.getOverlays().add(anotherItemizedIconOverlay);
 mapView.invalidate();
 return true;
 }


@Override
public boolean onDoubleTap(MotionEvent e, MapView mapView) {
//remove marker here
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
return true;
}
}; //end of Overlay

mapView.getOverlays().add(touchOverlay);



via Chebli Mohamed

Parsing Json in Java trouble with json format android

I 'm really new at this. I was working with Java and json.

The question I have is: How I can get the information from my .json file with the following format :

[{"name":"My name","country":"Country name"}]

I can now obtain with the following code:

Json file:

{"name":"My name","country":"Country name"}

Java file:

@Override
        protected JSONObject doInBackground(String... args) {

            JsonParser jParser = new JsonParser();
            JSONObject json;
            json = jParser.getJSONFromUrl("http://ift.tt/1KaewyN");

            System.out.println("JSON: " + json);

            if(json != null) {

                try {

                    name = json.getString("name");
                    country = json.getString("country");

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

            return null;
        }

But omitting the [] from my json file ):

How to get the same information without omitting anything of my json file?

I was reading about getJSONArray, and as I see, having my file [] , but I fail to understand well how to work with that file without the array holds "name".

Does anyone understand me? I must not omit [] from my json file .

Sorry for my English ):



via Chebli Mohamed

Custom List view adapter only showing 100 entries

I didn't use parse query adapter, instead i made a custom adapter and passed all the text and images in that but Parse only loads 100 items in that because Parse only has 100 entries on one page of the database. Can anyone tell me how to get to the next page of the database without using the parse query adapter?



via Chebli Mohamed

startactivity crashed on execute

I have setup an activity to be executed from a menu button. The activity is started and briefly appears and then crashes. I have added added activity to manifest file. Code poseted below. I have recently switched form Eclipse to Android Studio and still learning the changes.

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Titles_Edit_Activity"
        android:label="@string/title_activity_titles__edit_"
        android:theme="@style/Theme.AppCompat">
    </activity>
</application>

This is the logcat message: 08-13 11:13:45.841 15302-15302/com.example.jerry.els2015 D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002

Menu trigger in MainActivity

public void setup(MenuItem menuItem){

Log.d("TAG", "Setting   ");

startActivity(new Intent(this,Titles_Edit_Activity.class));

}

XML for Tiles_Edit_Activity

     package com.example.jerry.els2015;

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

public class Titles_Edit_Activity extends ActionBarActivity {

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

@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_titles__edit_, 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);
}
}

I found the issue on the activity. I setup menu and back button to finish and exit the system so bluetooth will be killed. I removed these option and was able to execute the new activity.

          @Override
protected void onDestroy() {
    super.onDestroy();
  //  finish();
  //  System.exit(0);
}

@Override
protected void onStop() {
    super.onStop();
//    finish();
 //   System.exit(0);


}



via Chebli Mohamed

Permission issue on MNC with Google Maps

I have created a minimal example that demos the problem in this question

http://ift.tt/1h6TGnE

I ran into this issue in a real app, but created this project to demo the minimal example.

The project was created with Android Studio 1.3.1

It was a "Google Maps Activity" project targeting MNC.

The only change I made was changing

compile 'com.android.support:appcompat-v7:23.+'

to

compile 'com.android.support:appcompat-v7:22.+'

as 23.+ doesn't seem to exist yet... (not sure why it's used by the project creation wizard)

On start up this exception is seen.

 Caused by: java.lang.SecurityException: The Maps API requires the additional following permissions to be set in the AndroidManifest.xml to ensure a correct behavior:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        at com.google.maps.api.android.lib6.d.t.a(Unknown Source)
        at com.google.maps.api.android.lib6.d.ft.a(Unknown Source)
        at com.google.maps.api.android.lib6.d.aj.a(Unknown Source)
        at com.google.maps.api.android.lib6.d.ai.a(Unknown Source)
        at com.google.android.gms.maps.internal.x.onTransact(SourceFile:107)
        at android.os.Binder.transact(Binder.java:387)
        at com.google.android.gms.maps.internal.IMapFragmentDelegate$zza$zza.onCreateView(Unknown Source)
        at com.google.android.gms.maps.SupportMapFragment$zza.onCreateView(Unknown Source)
        at com.google.android.gms.dynamic.zza$4.zzb(Unknown Source)
        at com.google.android.gms.dynamic.zza.zza(Unknown Source)
        at com.google.android.gms.dynamic.zza.onCreateView(Unknown Source)
        at com.google.android.gms.maps.SupportMapFragment.onCreateView(Unknown Source)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:924)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1116)
        at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1218)
        at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2170)
        at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:300)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:748)
        ... 19 more

as you can see in the manifest:

http://ift.tt/1J2MyhL

The permission in question is there.

The emulator is running the latest version of M.

Is there something I am missing to get maps to play nice in M? Like ask for the permission before I inflate the layout containing the map? Or am I just jumping the gun and I need to wait a bit longer for all of this to be ready for testing?

That seems like an annoying limitation to have to ask for the storage permission at startup for apps built around the map.

UPDATE: there is now a branch of the project that works.. here is the diff: http://ift.tt/1L9JWWj



via Chebli Mohamed

Simple upload to S3 from android

I've searched the web for ways to upload a simple file to s3 from android but couldn't find anything that work and I think it is because lack of concrete steps.

1.) http://ift.tt/1PaB2FW

That is the best guide I found but it does not tell what libraries to include. I downloaded the aws sdk for android and inside there were many jars. So intuitively, I included the aws-android-sdk-s3-2.2.5.jar however that is not complete. It does not have the class BasicAWSCredentials.

2.)I've looked at the more at the sample but it is not straightforward as #1 and I couldn't get the core upload functionality with credentials.

I appreciate your help



via Chebli Mohamed

Crosswalk project how to keep view alive

My app works with regular webview but it's very slow under Android 4.0 - 4.2 and just slow on 4.3 and 4.4.

I've already done lot of optimalizations in html/js/css, but still is too slow. So decided to take a look at Crosswalk project.

It's almost all great even with +20mb size for apk, except for one thing..

You cannot create XWalkView (equivalent of WebView) with Service context (like you can do with regular WebView) only Activity context is an option for Crosswalk view.

Why it's bad?

The website that I load into WebView/XWalkView uses WebSockets, it has to be always alive! But Android likes to kill apps, especially on older devices with Android 4.0-4.2.

Solution is to create WebView with Service context and keep reference to it in Service (Service is in foreground mode so hard to kill!).

Then if Activity will crash or will be garbage-collected, simply user taps to it, Activity recreates himself and gets reference to WebView (from Service class) to add it to his hierarchy again. :) (and in the meantime when activity didn't exist, webview was still working along with websocket connection)

All works, but with WebView and WebView is slow..

Why I am writing it? Need advice from you what to do or maybe solution how to force CrossWalk view to works with Service context.

Is it other way to keep XWalkView "always" alive?

Thanks!



via Chebli Mohamed

parse initialization is making the app crash

I am trying to use parse but parse told me to include the first code into the project to check if the data is transfered.... my app crashes...

I then followed a solution on stack overflow that explained how you have to initialize the parse in separate class and include it into manifest file... but after I followed it... my app still doesn't work... It crashes every single time..

Android manifest

   <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://ift.tt/nIICcg"
    package="com.example.parseexample"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="21" />

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity.java

package com.example.parseexample;


public class MainActivity extends Activity {

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


        ParseObject testObject = new ParseObject("TestObject");
        testObject.put("foo", "bar");
        testObject.saveInBackground();

    }


}

And this is my parseexample.java

    package com.example.parseexample;

    import com.parse.Parse;

    import android.app.Application;

    public class Initializeparse extends Application{

        @Override
        public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();

            Parse.enableLocalDatastore(getApplicationContext());

            Parse.initialize(getApplicationContext(), "lUdLAC7d7HXQfdv1g7SO0T70jcc6vIMIHJRlYEvE", "ObFeYoJE3dqJmxMSfMkCQx37MvAqQfrNvnXHr38v");

        }



    }

Logcat

    08-14 05:07:48.569: D/HyLog(3996): I : /data/font/config/sfconfig.dat, No such file or directory (2)
08-14 05:07:48.569: D/HyLog(3996): I : /data/font/config/dfactpre.dat, No such file or directory (2)
08-14 05:07:48.569: D/HyLog(3996): I : /data/font/config/sfconfig.dat, No such file or directory (2)
08-14 05:07:48.579: I/dalvikvm(3996): Could not find method com.parse.Parse.initialize, referenced from method com.example.parseexample.Initializeparse.onCreate
08-14 05:07:48.579: W/dalvikvm(3996): VFY: unable to resolve static method 19: Lcom/parse/Parse;.initialize (Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
08-14 05:07:48.579: D/dalvikvm(3996): VFY: replacing opcode 0x71 at 0x0007
08-14 05:07:48.579: D/AndroidRuntime(3996): Shutting down VM
08-14 05:07:48.579: W/dalvikvm(3996): threadid=1: thread exiting with uncaught exception (group=0x41a00e48)
08-14 05:07:48.579: E/AndroidRuntime(3996): FATAL EXCEPTION: main
08-14 05:07:48.579: E/AndroidRuntime(3996): Process: com.example.parseexample, PID: 3996
08-14 05:07:48.579: E/AndroidRuntime(3996): java.lang.NoClassDefFoundError: com.parse.Parse
08-14 05:07:48.579: E/AndroidRuntime(3996):     at com.example.parseexample.Initializeparse.onCreate(Initializeparse.java:14)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1007)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4432)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread.access$1500(ActivityThread.java:142)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1263)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.os.Looper.loop(Looper.java:136)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at android.app.ActivityThread.main(ActivityThread.java:5120)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at java.lang.reflect.Method.invoke(Method.java:515)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
08-14 05:07:48.579: E/AndroidRuntime(3996):     at dalvik.system.NativeStart.main(Native Method)



via Chebli Mohamed

Android eclipse xml formatting issue

Hello i have a xml file which doesent seem to work, i am trying to reach it with a listpreference.

Here is the listpreference code:

<PreferenceCategory android:name="@string/yo_category">

<ListPreference
    android:title="YOYO"
    android:key="YOYOYO"
    android:summary="YODOBO"
    android:entries="@+arrays/yoyo"
    android:entryValues="@+arrays/yoyoValues"
></ListPreference>

</PreferenceCategory>  

And here is the xml file:

<string-array name="yoyo">
    <item>1 yoyo</item>
    <item>2 yoyos</item>
    <item>3 yoyos</item>
</string-array>
<string-array name="yoyoValues">
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>

And i cannot seem to find the issue here, i get no errors in eclipse but when i try to run it i cant see the items in the listpreference.

Thanks for any help!



via Chebli Mohamed

App Users not set as registered as Subscribers

I have no idea why my app users (in production) are not getting added to my notification send list. When I used my 2 test devices they worked fine and got added to the list.

Am I missing something? I believe my code is fine as it works for my devices at home.

public class AppFirst extends Application {

  @Override

  public void onCreate() {

  super.onCreate();



// Add your initialization code here

Parse.initialize(this, "XXXX", "XXX");

ParseInstallation.getCurrentInstallation().saveInBackground();



ParsePush.subscribeInBackground("", new SaveCallback() {



    @Override

    public void done(com.parse.ParseException e) {

        // TODO Auto-generated method stub

         if (e == null) {

              Log.d("com.parse.push", "successfully subscribed to the broadcast channel.");

            } else {

              Log.e("com.parse.push", "failed to subscribe for push", e);

            }



    }

});





ParseUser.enableAutomaticUser();

ParseACL defaultACL = new ParseACL();

// Optionally enable public read access.

// defaultACL.setPublicReadAccess(true);

ParseACL.setDefaultACL(defaultACL, true);

  }

}



via Chebli Mohamed

I can't import card library in my Android Studio

Today I install Android Studio in my new Pc, I tried to start a new project but I couldn´t because I have this error when I try to compile some new library of Material Design as CardView or RecyclerView, I was reading about this problem and I tried to do everything, I installed all SDK, I change the library versions a lot times, but I cant resolve this =(.

This is the picture of my error:

My Error

Please, any help will be greatfully. I can´t program if I dont resolve this.



via Chebli Mohamed

How to send parse push to devices near a particular geopoint & to a channel?

I am using parse to push data to a set of android devices which are near a particular geopoint. I have successfully created a geopoint from the device into the installationData. I want to push data to a particular channel and filter by those devices near the geopoint. But when i push this data from REST API i get 400 Bad Request error:

{"where":{"channels":"NewReq","user":{"$inQuery":{"location":{"$nearSphere":{"__type":"GeoPoint","latitude":30.0,"longitude":-20.0},"$maxDistanceInMiles":1.0}}}},"data":{"custid":118,"fromadd":"uuhuh","orderid":"BT8224847","type":"NewTowRequests","paymenttype":"Cash","custdevid":"APA91bEgSVTkS4M4YXJbIlRUx_8LfPMnnpvWKUEobHpO6bVZ-086n2uRalyeql98oy9ifyoUXARJuki1SEYIBCuHHIJXe8Jn9YLbQRQ3VdJqGEaDXFxRDys","fromlat":30.0,"fromlon":-20.0,"rating":0.0,"ordertype":"SCH","sch_date":"25/08/2015 16:00","is_sch":"True","status":"PEN","is_rec":"False","orderdate":"13/08/2015 07:38"}} 

Note that i have not created any users , isn't there a method to send it to the devices near a geopoint without creating the users?



via Chebli Mohamed

Can I use an Android application project as a library in Android Studio?

In particular, I want to use some of the code in ExoPlayer's demo as a library, in addition to the library module. Is this possible in Android Studio? (I'm a little bit new).

Thanks.



via Chebli Mohamed

How to delete snapshot from Google Games in Android

Im implementing the snapshots from google games to my game, but i dont want to use the interface they use, I want to implement the open, update and delete gamedata in my game.

For the operations open and update i have no issue and everything works perfect, but for the delete operation I have a problem.

Based on the samples for open and update I managed to create a code that works but just halfway:

//get the snapshot
String snapshotName = "My_Snapshot_0";
Snapshots.OpenSnapshotResult open = Games.Snapshots.open(mGoogleApiClient, snapshotName, false).await();
if (!open.getStatus().isSuccess()) {
    Log.w(TAG, "Could not open Snapshot for update.");
    return false;
}
//delete the snapshot
Snapshots.DeleteSnapshotResult delete = (Snapshots.DeleteSnapshotResult)Games.Snapshots.delete(mGoogleApiClient, open.getSnapshot().getMetadata()).await();

if (!delete.getStatus().isSuccess()) {
    Log.w(TAG, "Failed to delete Snapshot.");
    return false;
}

This code its supposed to delete the snapshot My_Snapshot_0 and it even returns success, but if I try to recreate the snapshot (using the same name), an error is returned because it could not open the snapshot. This means the deleting process is missing something to work correctly.

After trying to recreate it and fail, if I do it again (repeat recreate process), then there is no error and the snapshot is created without any problem.

Its weird how the Games.Snapshots.delete uses an snapshot metadata instead of the snapshot.

The documentation says little about deleting and in the samples google provide there is no sample code for doing this correctly.

Thanks in advance!



via Chebli Mohamed

I am doing a project in Java with Android jni C++. I have a function in C++ with the following parameters:

C++ function: void rectify (vector <Point2f> & corners, Mat & img) {...}

In JAVA, call would be:

Mat image = Highgui.imread("img.png");
List <MatOfPoint> cornners =  new ArrayList<MatOfPoint>();;
Point b = new Point (real_x2, real_y2);
MatOfPoint ma = new MatOfPoint (b);
cornners.add(ma);
rectfy(image.getNativeObjAddr(), cornners)

public native void rectfy(long mat, "??" matofpoint);

With that, I wonder how will the function C++ jni:

JNIEXPORT void JNICALL Java_ImageProcessingActivity_rectfy (JNIEnv * jobject, ?? cornners, inputMatAddress jlong)



via Chebli Mohamed

null pointer exception when sending ISO8583 request

I am trying to send an ISO8583 request to a terminal using the following code:

try {
        XMLParser packager = new XMLParser(this.xmlFile);


        final ISOMsg isoMsg = new ISOMsg();
        isoMsg.setPackager(packager);
        isoMsg.setMTI("0800");
        isoMsg.set(3, "xxxxxx");
        isoMsg.set(7, "xxxxxxxxxx");    //MMDDhhmmss
        isoMsg.set(11, "xxxxxx");
        isoMsg.set(12, "084500");       //Time of the message HHmmss
        isoMsg.set(13, "0621");         //Date MMDD
        isoMsg.set(41, "xxxxxxxx");
        isoMsg.set(62,"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        isoMsg.set(63,"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
        BaseChannel channel = new BaseChannel() {};
        channel.setLogger(logger, "server-request-channel");
        channel.setHeader(isoMsg.pack());
        channel.setHost("xx.xx.xx.xx", xxxxx);
        ISOMUX isoMux = new ISOMUX(channel) {
            @Override
            protected String getKey(ISOMsg m) throws ISOException {
                return super.getKey(m);
            }
        };

        isoMux.setLogger(logger, "server-request-mux");
        new Thread(isoMux).start();
        ISORequest req = new ISORequest(isoMsg);
        isoMux.queue(req);
        req.setLogger(logger, "server-request-logger");
        ISOMsg response = req.getResponse(50 * 1000);

        if (response != null) {
                System.out.println("Req ["+ new String(isoMsg.pack()) + "]");
                System.out.println("Res ["+ new String(response.pack()) + "]");
            }else{
                System.out.println("Timeout");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

After executing the code, I get the following exception:

<log realm="server-request-mux" at="Fri Aug 14 00:26:43 WAT 2015.995">
    <muxreceiver>
        <exception name="null">
            java.lang.NullPointerException
            at org.jpos.iso.BaseChannel.createISOMsg(BaseChannel.java:561)
            at org.jpos.iso.BaseChannel.createMsg(BaseChannel.java:558)
            at org.jpos.iso.BaseChannel.receive(BaseChannel.java:585)
            at org.jpos.iso.ISOMUX$Receiver.run(ISOMUX.java:263)
            at java.lang.Thread.run(Thread.java:856)
        </exception>
    </muxreceiver>
</log>

I added break point so as to find out the line causing the exception and discovered that the exception occurs whenever it encounters the statement:

ISORequest req = new ISORequest(isoMsg);

I am relatively new to ISO8583 jpos financial programming and I want to building an app on android platform.

How do I get over this exception?



via Chebli Mohamed

which is the best for GUI C++ Qt or C# or JAVA 2015

hi i want to ask you a question i had learn c++ and something about the framework Qt but the problem that now day the Qt is not used in the world of apps smartphone like C# or JAVA !! so do u leave c++ and Qt and start with C# or JAVA ?? please i need your Advice Thank you



via Chebli Mohamed

Add an element from a listView to another listView

I want to create an add to favorites action bar button on the news and to add it to a new list adaptor in the favorites tab, can you help me please implementing the button an how to create the new list?

here is my code: (displaying the clicked news)

    public class ListItemClicked extends ActionBarActivity {

    static Bundle extras;

    SectionsPagerAdapter mSectionsPagerAdapter;
    static ImageLoader imageLoader;
    static DisplayImageOptions options;




    ViewPager mViewPager;

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


        mSectionsPagerAdapter = new  SectionsPagerAdapter(getSupportFragmentManager());

        extras = getIntent().getExtras();

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

        //Setup the ImageLoader, we'll use this to display our images
        ImageLoaderConfiguration config = new  ImageLoaderConfiguration.Builder(this).build();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(config);

        //Setup options for ImageLoader so it will handle caching for us.
        options = new DisplayImageOptions.Builder()
                .cacheInMemory()
                .cacheOnDisc()
                .build();

    }


    @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_activity2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        return id == R.id.action_settings || super.onOptionsItemSelected(item);

    }



    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section4).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section5).toUpperCase(l);
            }
            return null;
        }
    }


    public static class PlaceholderFragment extends Fragment {


        private static final String ARG_SECTION_NUMBER = "section_number";


        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState)
        {

            View rootView = inflater.inflate(R.layout.fragment_list_item_clicked, container, false);


            TextView pDate = (TextView) rootView.findViewById(R.id.textView);
            pDate.setText( extras.getString("pdate") );


            TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
            ptitle.setText(extras.getString("pname"));


            TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
            pnText.setText( extras.getString("pText"));




            //Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
            ImageLoadingListener listener = new ImageLoadingListener(){



                @Override
                public void onLoadingStarted(String arg0, View arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLoadingCancelled(String arg0, View arg1) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
                    // i/ndicator.setVisibility(View.INVISIBLE);
                    // iconImg.setVisibility(View.VISIBLE);
                }
                @Override
                public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
                    // TODO Auto-generated method stub

                }

            };

            //Load the image and use our options so caching is handled.
            final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
            imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);



            return rootView;
        }
    }

}

the first list adaptor with news news from list adaptor clicked the favorites tab



via Chebli Mohamed

Save radiogroup state on activity change

I know there have been posts on how to save radiogroup states on activity change via SharePrefs. My problem is slightly different. I have a listview that generates multiple radiogroups dynamically. How can I make sure when a user leaves the current activity that each of the listview radiogroups are saved?? Below is my current adapter class showing my getView method.

 @Override
 public View getView(final int position, final View convertView, ViewGroup parent) {
  View v = convertView;

  final ViewHolder holder;
  if(v == null) {
     v = mInflater.inflate(R.layout.list_item_car, parent, false);
     holder = new ViewHolder();
     holder.txtCarName = (TextView) v.findViewById(R.id.txt_car_name);
     holder.radioGroup = (RadioGroup) v.findViewById(R.id.scale);

     holder.radioGroup.setTag(position);
     v.setTag(holder);


  }
  else {
     holder = (ViewHolder) v.getTag();
  }

  // fill row data
  final Car currentItem = getItem(position);
  if(currentItem != null) {
     holder.txtCarName.setText(currentItem.getCar());
     holder.radioGroup.setTag(currentItem.getAnswer());
  }


  holder.radioGroup.setOnCheckedChangeListener(null);
  holder.radioGroup.clearCheck();

  if(checked.indexOfKey(position)>-1){
     holder.radioGroup.check(checked.get(position));
  }else{
     holder.radioGroup.clearCheck();
  }

  holder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

     @Override
     public void onCheckedChanged(RadioGroup group, int checkedId) {

        String Answer = null;
        if(checkedId>-1){
           checked.put(position, checkedId);


           switch (checkedId) {
              case R.id.a1:
                 Answer = "r1";
                 break;
              case R.id.a2:
                 Answer = "r2";
                 break;
              case R.id.a3:
                 Answer = "r3";
                 break;
              case R.id.a4:
                 Answer = "r4";
                 break;
           }

           db.addListItem(“testCar", Answer, getCurrentTimeStamp());  //<----null object reference happening here


        }else{
           if(checked.indexOfKey(position)>-1)
              checked.removeAt(checked.indexOfKey(position));
        }

     }
     });



  return v;
  }



via Chebli Mohamed

Google Play Android Wear: This app is incompatible with your decide

I published my first Android Wear watch face today, but I could not download it onto my watch since it was not compatible with my android phone device. I understand it is because I don't have a corresponding application for mobile, but there a way to do this without having a mobile application. I don't want ta mobile application since it will be useless for the user because it adds no customization for the watch face.



via Chebli Mohamed

Null pointer exception in android google maps

I'm trying to add google maps to my app. The logcat window shows this error: Caused by: java.lang.NullPointerException at com.example.mymaps.MainActivity.onCreate(MainActivity.java:27) at android.app.Activity.performCreate(Activity.java:5104) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080).

How to remove this error?

   Main xml:
   <RelativeLayout     
   xmlns:android="http://ift.tt/nIICcg"
   xmlns:tools="http://ift.tt/LrGmb4"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity" >

  <fragment
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment" />

 </RelativeLayout>

Main Java import android.app.Activity; import android.os.Bundle; import android.view.Menu;

  import com.google.android.gms.maps.CameraUpdateFactory;

  import com.google.android.gms.maps.GoogleMap;
  import com.google.android.gms.maps.MapFragment;
  import com.google.android.gms.maps.model.BitmapDescriptorFactory;
  import com.google.android.gms.maps.model.LatLng;
  import com.google.android.gms.maps.model.Marker;
  import com.google.android.gms.maps.model.MarkerOptions;

  public class MainActivity extends Activity {
  static final LatLng HAMBURG = new LatLng(53.558, 9.927);
  static final LatLng KIEL = new LatLng(53.551, 9.993);
  private GoogleMap map;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
    .getMap();
     Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
    .title("Hamburg"));
     Marker kiel = map.addMarker(new MarkerOptions()
    .position(KIEL)
    .title("Kiel")
    .snippet("Kiel is cool")
    .icon(BitmapDescriptorFactory
        .fromResource(R.drawable.ic_launcher)));

    // Move the camera instantly to hamburg with a zoom of 15.
    map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

    // Zoom in, animating the camera.
   map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
   }

    @Override
   public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.activity_main, menu);
   return true;
   }

  } 

LogCat window:

08-13 23:32:27.279: E/AndroidRuntime(1010): FATAL EXCEPTION: main 08-13 23:32:27.279: E/AndroidRuntime(1010): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mymaps/com.example.mymaps.MainActivity}: java.lang.NullPointerException 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.ActivityThread.access$600(ActivityThread.java:141) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.os.Handler.dispatchMessage(Handler.java:99) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.os.Looper.loop(Looper.java:137) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.ActivityThread.main(ActivityThread.java:5039) 08-13 23:32:27.279: E/AndroidRuntime(1010): at java.lang.reflect.Method.invokeNative(Native Method) 08-13 23:32:27.279: E/AndroidRuntime(1010): at java.lang.reflect.Method.invoke(Method.java:511) 08-13 23:32:27.279: E/AndroidRuntime(1010): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) 08-13 23:32:27.279: E/AndroidRuntime(1010): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) 08-13 23:32:27.279: E/AndroidRuntime(1010): at dalvik.system.NativeStart.main(Native Method) 08-13 23:32:27.279: E/AndroidRuntime(1010): Caused by: java.lang.NullPointerException 08-13 23:32:27.279: E/AndroidRuntime(1010): at com.example.mymaps.MainActivity.onCreate(MainActivity.java:27) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.Activity.performCreate(Activity.java:5104) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 08-13 23:32:27.279: E/AndroidRuntime(1010): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144) 08-13 23:32:27.279: E/AndroidRuntime(1010): ... 11 more



via Chebli Mohamed

E/AndroidRuntime(274): java.lang.RuntimeException: An error occured while executing doInBackground()

pliiiiiiiiiiiiiiiiz help me i am trying to program an application android but i have an error in my aplication whene i click the button

here is the error:

08-13 22:50:56.182: E/AndroidRuntime(276): FATAL EXCEPTION: AsyncTask #1
08-13 22:50:56.182: E/AndroidRuntime(276): java.lang.RuntimeException: An error occured while executing doInBackground()
08-13 22:50:56.182: E/AndroidRuntime(276):  at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.lang.Thread.run(Thread.java:1096)
08-13 22:50:56.182: E/AndroidRuntime(276): Caused by: java.lang.NullPointerException
08-13 22:50:56.182: E/AndroidRuntime(276):  at com.example.massarv4.Login$AttemptLogin.doInBackground(Login.java:78)
08-13 22:50:56.182: E/AndroidRuntime(276):  at com.example.massarv4.Login$AttemptLogin.doInBackground(Login.java:1)
08-13 22:50:56.182: E/AndroidRuntime(276):  at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-13 22:50:56.182: E/AndroidRuntime(276):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

login.java

import java.util.ArrayList;
import java.util.List; 
import org.apache.http.NameValuePair; 
import org.apache.http.message.BasicNameValuePair; 
import org.json.JSONException; 
import org.json.JSONObject;

import com.example.massarv4.JSONParser;
import com.example.massarv4.OtherActivity;

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle; 
import android.util.Log;
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText;
import android.widget.Toast; 
public class Login extends Activity implements OnClickListener{ 
    private EditText user, pass; 
    private Button bLogin;
    // Progress Dialog 
    private ProgressDialog pDialog; 
    // JSON parser class 
    JSONParser jsonParser = new JSONParser(); 
    private static final String LOGIN_URL = "http://ift.tt/1TxPFcU"; 
    private static final String TAG_SUCCESS = "success"; 
    private static final String TAG_MESSAGE = "message";
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.login);
        user = (EditText)findViewById(R.id.username); 
        pass = (EditText)findViewById(R.id.password); 
        bLogin = (Button)findViewById(R.id.login);
        bLogin.setOnClickListener(this);
        } 
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub 
        switch (v.getId()) { 
        case R.id.login: new AttemptLogin().execute(); 
        // here we have used, switch case, because on login activity you may
        //also want to show registration button, so if the user is new ! we can go the 
        //registration activity , other than this we could also do this without switch //case. 
        default: break; 
        }
        } 
    class AttemptLogin extends AsyncTask<String, String, String> {
        /** * Before starting background thread Show Progress Dialog * */ 
        boolean failure = false;
        @Override
        protected void onPreExecute() { 
            super.onPreExecute();
            pDialog = new ProgressDialog(Login.this);
            pDialog.setMessage("Attempting for login...");
            pDialog.setIndeterminate(false); 
            pDialog.setCancelable(true); pDialog.show(); 
            } 
        @Override
        protected String doInBackground(String... args) { 
            // TODO Auto-generated method stub // here Check for success tag 
            int success=0; 
            String username = user.getText().toString();
            String password = pass.getText().toString();
            try {
                List<NameValuePair> params = new ArrayList<NameValuePair>(); 
                params.add(new BasicNameValuePair("username", username));
                params.add(new BasicNameValuePair("password", password)); 
                Log.d("request!", "starting"); 
                JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); 
                // checking log for json response 
                Log.d("Login attempt", json.toString());
                // success tag for json 
                success = json.getInt(TAG_SUCCESS); 
                if (success == 1) { Log.d("Successfully Login!", json.toString());
                Intent ii = new Intent(Login.this,OtherActivity.class); finish(); 
                // this finish() method is used to tell android os that we are done with current 
                //activity now! Moving to other activity 
                startActivity(ii);
                return json.getString(TAG_MESSAGE);
                }else{ 
                    return json.getString(TAG_MESSAGE); 
                    } }
            catch (JSONException e) { 
                e.printStackTrace(); 
                } 
            return null; 
            }
        /** * Once the background process is done we need to Dismiss the progress dialog asap * **/ 
        protected void onPostExecute(String message) { pDialog.dismiss()
            ; if (message != null){
                Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show(); 
                }
            }
        }



        }

login.php

<?php mysql_connect("localhost","root",""); 
$db= mysql_select_db("massar"); 
$pas=$_POST["password"];
$usr=$_POST["username"];
if (!empty($_POST)) { 
    if (empty($_POST['username']) || empty($_POST['password'])) { 
    // Create some data that will be the JSON response 
    $response["success"] = 0; $response["message"] = "One or both of the fields are empty ."; 
    //die is used to kill the page, will not let the code below to be executed. It will also //display the parameter, that is the json data which our android application will parse to be 
    //shown to the users 
    die(json_encode($response)); 
    } 
    $query = " SELECT * FROM parent WHERE CIN = $usr and MotDePasse = $pas "; 
    $sql1=mysql_query($query); 
    $row = mysql_fetch_array($sql1); 
        if (!empty($row)) { 
    $response["success"] = 1; 
    $response["message"] = "You have been sucessfully login";
    die(json_encode($response));
    } else{ 
        $response["success"] = 0; 
        $response["message"] = "invalid username or password "; 
        die(json_encode($response)); } } else{ $response["success"] = 0; 
        $response["message"] = " One or both of the fields are empty "; 
        die(json_encode($response));
        } mysql_close(); 
        ?>

i need your help pliiz I got stuck



via Chebli Mohamed

Converting Image to Textual form to send over SMS

Is there any way that i can convert image to textual representation so that i can send it via SMS and convert back to image after receiving on the other end. By doing this i'll be able to share media files without internet/mms i-e mms will be converted to sms.

I want to know that if it's even possible or not? if possible then how? The only issue is the conversion of images to text and vice versa.



via Chebli Mohamed

Mailcore2 on Android storeFlags operation hangs

I'm trying to set the delete flag on a message, and when I run start() on the storeFlags operation, it hangs, and the emulator says the application has stopped running. Here's my code:

IndexSet set = IndexSet.indexSetWithIndex(message.uid());
IMAPOperation setDeleteFlagOperation = 
    MessagesSyncManager.singleton().session.storeFlagsByUIDOperation(
        "INBOX", set, IMAPStoreFlagsRequestKind.IMAPStoreFlagsRequestKindSet, 
        MessageFlag.MessageFlagDeleted);
setDeleteFlagOperation.start(this);

I've also tried using storeFlagsByNumberOperation() to create the operation with the same result. I've made sure that I pass in a valid UID, or in the case of storeFlagsByNumberOperation(), a valid sequence number. Can you tell me what I'm doing wrong?



via Chebli Mohamed

Why is my GoogleMap leaking its parent ViewGroup?

My app is leaking the root layout of one of its activities every time that activity is destroyed. Merging shortest paths to GC roots shows only one root for each leaked instance, and the path is all Google Maps API classes:

com.google.android.gms.location.internal.t @ 0x42387220 Native Stack
'- a com.google.android.gms.location.internal.s @ 0x42387268
   '- a com.google.maps.api.android.lib6.d.v @ 0x425f73a0
      '- c com.google.maps.api.android.lib6.d.aj @ 0x4261f5d8
         '- i com.google.maps.api.android.lib6.gmm6.c.a @ 0x425fbbf0
            '- d com.google.maps.api.android.lib6.gmm6.c.y @ 0x42754cd0
               '- mParent android.widget.FrameLayout @ 0x4261f678
                  '- mParent android.widget.FrameLayout @ 0x4245c6c0
                     '- mParent android.widget.RelativeLayout @ 0x4254ca08

I'm not using FrameLayout anywhere, so I assume that's part of the MapFragment UI.

What could I possibly be doing to cause this? The activity doesn't do anything with the map except call setMyLocationEnabled(true) on it. I'm not creating any markers or anything.

This is how the fragment is declared in the activity XML:

<fragment
    android:name="com.google.android.gms.maps.MapFragment"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/fake_status_bar"
    android:layout_toRightOf="@id/leftButtons"
    android:layout_margin="3dp" />

I'm using google-play-services_lib version 26, which is the latest.



via Chebli Mohamed

Smali function: Return an Integer

I know how to return a TRUE boolean from a function:

.locals 1
const/4 v0, 0x1
return v0

Now I need to return an integer (10000 value). How?



via Chebli Mohamed

how can we use Buildconfig That is automatically generated?

Builds Config is automatically generated . But when i call This in another method it throws some error .

I also import This Build Config into my java class but it shows unused import statement . should i need to add something in Android Manifest ?



via Chebli Mohamed

How show text in centre of each rectangle using onDraw

I'm trying to create a text view (black colour) containing numbers 1 to 7 (each number on top and in the centre of each grey rectangle - just like the image I've drawn below) but I'm not sure what properties I need to add in order to achieve this. I believe the code needs to go in the loop section but I don't what code. What can be done so that a number appears centralised in each grey rectangle?

desired outcome

enter image description here

current outcome

enter image description here

public class RectangleTextView extends View {
    private final Paint mBackPaint = new Paint();
    private final Paint mRedPaint = new Paint();
    private int mSideRectWidth = 10;

    public RectangleTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mBackPaint.setColor(Color.BLACK);
        mRedPaint.setColor(Color.RED);
    }

    @Override protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (getWidth() == 0)
            return;

        //draw grey boxes
        setBackgroundColor(Color.parseColor("#808080"));
        int boxWidth = getWidth() / 7;

        //draw black lines and/or draw text in centre of each rectangle
        for (int i = 0; i < 7; i++) {
            canvas.drawLine(mSideRectWidth + boxWidth * i, 0, mSideRectWidth + boxWidth * i, getHeight(), mBackPaint);
        canvas.drawText(?);
        }

        //draw text in centre of each rectangle
        ?

        //draw left end rectangle
        canvas.drawRect(0, 0, mSideRectWidth, getHeight(), mRedPaint);

        //draw right end rectangle
        canvas.drawRect(getWidth() - mSideRectWidth, 0, getWidth(), getHeight(), mRedPaint);
    }
}



via Chebli Mohamed

weird behavior when receiving push notifications

So I followed Parse's guide on setting up push notifications yesterday. I left the client channel to "" for Broadcast. And when I tried to send notifications, My phone didn't receive any. After trying to trouble shoot for a while I gave up and went to bed.

Then I was waken up by my phone buzzing at 6 in the morning. I look at it and it's the dozen push notifications I sent like 8 hours earlier. (To be clear when I sent them I set the all to now. I didn't schedule them). So when I try to send them today it didn't work. I tried switching the channel and it worked. I sent a push notification and my phone received it instantly. After that I went to eat, came back and tried to test some things out and my phone doesn't receive them anymore.

Has anyone ever noticed behavior like this or know what the problem might be. Parse tells me that they send just fine and I don't know if it's an issue with my code because it CAN receive them.



via Chebli Mohamed

How to draw Canvas in WebView?

I'm making an app where people will be able to place circles in WebView. So, my algorithm is:

  1. Detect long click
  2. Get finger coordinates on WebView
  3. Draw circle in Canvas

I tried different methods, used different approaches - making personal DrawWebView class, detecting long press in MainActivity and then drawing circle in DrawView and list goes on, yet nothing works.

For starters I decided to set up custom WebView and draw circle in fixed position(330, 618). I manage to draw it, but when I start to zoom in, circle moves.

public class DrawWebView extends WebView{

    PointF zoomPos;
    static DrawWebView wv1;
    public DrawWebView (Context context, AttributeSet attrs)
    {
        super (context, attrs);
        wv1 = (DrawWebView) findViewById(R.id.webView1);
        wv1.loadUrl("file://" + Environment.getExternalStorageDirectory() + "/Pictures/boxes.jpg");
        wv1.getSettings().setBuiltInZoomControls(true);
        wv1.getSettings().setDisplayZoomControls(false);
        wv1.getSettings().setSupportZoom(true);
        wv1.getSettings().setUseWideViewPort(true);
        wv1.getSettings().setLoadWithOverviewMode(true); 
        wv1.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    }

    public boolean onTouch(View v, MotionEvent event) {

        int action = event.getAction(); 


        switch (action) { 
        case MotionEvent.ACTION_DOWN:
            break;
        case MotionEvent.ACTION_MOVE:
            this.invalidate();
            break;

        case MotionEvent.ACTION_UP: 
            this.invalidate();
            break;
        case MotionEvent.ACTION_CANCEL:

            break; 

        default: 
            break; 
        }
        return true;
    }


    @Override
    protected void onDraw(Canvas canvas) 
    {
        super.onDraw (canvas);

        zoomPos = MainActivity.zoomPos;
        Paint p = new Paint();
        p.setColor (Color.RED);
        canvas.drawCircle(330, 618, 10, p);
        //canvas.drawCircle(100, 100, 100, p);


    }
}

If you know how to do this or know a good tutorial - it would be much appreciated.



via Chebli Mohamed

Out of memory after some image creation

in my application I create some foto on button click where I take the screen view and thene I merge this image with 2 logo, the app with 5,10 image don't have problem but with more the 10 image I get an out of memory, this is the code:

    @Override
    public void onScreenshotImage(ImageStruct image) {
        //do whatever you want with the image parameter

        super.onScreenshotImage(image);

        Bitmap a = image.getBitmap();

        ResizeImage resize = new ResizeImage(a);
        resize.execute();

        Log.d("onScreenshot","get image");
    }

private class ResizeImage extends AsyncTask<String, Void, String> {
    Bitmap bottomImage;

    public ResizeImage (Bitmap image) {
        bottomImage = image;
    }

    @Override
    protected String doInBackground(String... params) {

        Bitmap output = Bitmap.createBitmap(bottomImage.getWidth(), bottomImage.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Paint paint = new Paint();
        paint.setAntiAlias(true);

        canvas.drawBitmap(bottomImage, 0, 0, paint);

        Bitmap a = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
        canvas.drawBitmap(a, 0, 0, paint);
        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.logo_1);
        canvas.drawBitmap(b, bottomImage.getWidth()-(b.getWidth()+20), bottomImage.getHeight()-(b.getHeight()+30), paint);

        String outputString = Environment.getExternalStorageDirectory().getPath() + "/images/";

        File folder_thumb= new File(outputString);
        if (!folder_thumb.exists()) {
            folder_thumb.mkdirs();
        }

        String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
        OutputStream os = null;
        try {
            os = new FileOutputStream(outputString + tmpImg);
            output.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.close();
        }
        catch(IOException e) {
            Log.e("combineImages", "problem saving images", e);
        }

        a.recycle();
        b.recycle();
        output.recycle();
        bottomImage.recycle();

        return "Executed";
    }

    @Override
    protected void onPostExecute(String result)  {
        System.gc();
        Runtime.getRuntime().gc();
    }
}

ps. the first funciton is the function for get the image in metaio. where is the mistake?

edit: I saw that waiting for the end of the task the memory does not exceed tot mb , while removing the block ( a simple boolean ) memory also goes to 100mb.



via Chebli Mohamed

Storing data in Android - Java

I am currently working on my first app and i have decided to do it on android. I have the main activity layout the way i wish and the Time/Date displaying dynamically.

What I am needing help with is I need the app to save the date and time whenever a button is pressed. This data will need to be available for 1 week (7 Days) and then it may be overwritten the following week to save space on the device.

Ideally there would be two button presses a day, one to clock in/clock out (App to keep track of my hours at work and calculate pay). What is the best way to go about this? Can you guys point me in the right direction to storing this data?

I thought about using Parse but then an online connection would be needed, correct? Is there anyway to do this locally and then maybe I can implement online storage later?



via Chebli Mohamed

Copying custom json object to clipboard with javascript

I'm developing a shared canvas using HTML5 + javascript. I am developing copying/pasting functionality, and I have no problems to do it with Ctrl+C, +X, +V, but I also would like to add the typical buttons that provide the same functionality (mainly intended to be able to copy/paste in tablets).

The code to manage the standard events is quite straigtforward:

window.addEventListener("copy", copyFunc);

...

copyFunc(e){
  if (BDKanvasInstance.selection !== null){
    var data = BDKanvasInstance.selection.serialize();
    var jsonData = JSON.stringify(data);
    e.clipboardData.setData('application/json', jsonData);
    e.preventDefault();
  }
}

But I have to way to access the clipboardData from a button...

copyBtn.addEventListener("click", copyBtnFunc);

copyBtnFunc(e){
  /* Any way to access clipboardData or to trigger the standard copy command? */
}

I've seen several solutions involving creating a textarea, inserting the text, selecting it programmatically and using "execCommand('copy')", but that does not copy the text with an "application/json" type...

Any solutions? With a computer using keyboard shortcuts is ok, but they are not a solution when using it on the tablet...

Thank you!



via Chebli Mohamed

Android to PHP session without cookies

so far, I have been able to use the HttpURLConnection class in java to make an app that can GET the form of my php website, put in the proper login details (username, password) and POST them back. I have double checked this with the response codes and am getting 200 for both GET and POST.

I'm having an issue now accessing the page that a successful login should redirect to. It is to my understanding that after a POST or GET, the connection is terminated once the response code is requested. My attempts to get the response cookies while logging in produce a "null" cookie.

The PHP site I am accessing does not seem to have any response cookies after a login when using "inspect element" in Chrome. Regardless of this, I have tried accessing the cookies all sorts of ways with no such luck. The request cookie header is there when I go the the website.

Am I missing something and the cookies are actually there? Or is it possible that the site does not use cookies to maintain a session? If that's the case, how would I access the page I want after logging in on my Android app?

Response Headers
    Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
    Connection:Keep-Alive
    Content-Encoding:gzip
    Content-Length:23030
    Content-Type:text/html; charset=utf-8
    Date:Mon, 10 Aug 2015 23:03:26 GMT
    Expires:Thu, 19 Nov 1981 08:52:00 GMT
    Keep-Alive:timeout=15, max=100
    Pragma:no-cache
    Server:Apache/2.2.22 (Debian)
    Vary:Accept-Encoding
    X-Powered-By:PHP/5.4.4-14+deb7u11



Request Header
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:52
Content-Type:application/x-www-form-urlencoded
Cookie:__utma=83554121.1278939357.1435860313.1435944069.1438202297.3; __utmc=83554121; __utmz=83554121.1438202297.3.3.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); _ga=GA1.2.1278939357.1435860313; PHPSESSID=4q03j4ihb7trnm1pvvofc9f3f5
Host:WEBSITE
Origin:WEBSITE
Referer:WEBSITE
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36



via Chebli Mohamed

Why can't Loaders be non-static inner classes?

When I try to use a non-static inner Loader class, I get the following runtime error:

Object returned from onCreateLoader must not be a non-static inner member class

What's the point of this restriction?



via Chebli Mohamed

Android DatePicker's date saving and loading

I'm trying to save a Datepicker's date into a file, and when opening the app read it back from last time and set the date on it accordingly (if it is the first time and no file was saved already, set it to Jan 1 2000). All widgets such as editText, names, gender, etc work correctly, except DatePicker.

For some reasons it doesn't work. Can someone help with that? There is no concern on the file IO part; probably there are some Calendar/Date compatibility issues I guess.

When loading:

Date BD=new Date(2000,0,1);
        // Loading (w/o exception handling code):
        try {
            FileInputStream fis = this.openFileInput(fileName);
            ObjectInputStream is = new ObjectInputStream(fis);
            Object[] formData = (Object[]) is.readObject();
            is.close();
            fis.close();

            // parse data from array
        BD=(Date) formData[0];
//there are other fields as well

    } catch (FileNotFoundException e) {
        // TODO if for the first time- No data file exists
        // sets initial default value
    } 
    catch (IOException e) {
    } 
    catch (ClassNotFoundException e) {
    }

    //set value for BD
    final DatePicker BDDatePicker = (DatePicker) findViewById(R.id.datePickerBD);
    BDDatePicker.updateDate(BD.getYear(), BD.getMonth(), BD.getDate());

And for saving:

    final DatePicker BDdatePicker = (DatePicker) findViewById(R.id.datePickerBD);
    Date BD= getDateFromDatePicker(BDdatePicker);
    Object [] formData=new Object [7];

    formData [0]=BD;


    //Saving (w/o exception handling code):
    FileOutputStream fos;
    try {
        fos = this.openFileOutput(fileName, Context.MODE_PRIVATE);
        try {
            ObjectOutputStream os = new ObjectOutputStream(fos);
            os.writeObject(formData);
            fos.close();
            os.close();
        } catch (IOException e) {
        }
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
    }



via Chebli Mohamed

Error while compiling Google Services on Android Studio

So I am trying to add Google Services to my existing application (http://ift.tt/1uCoApM), however, upon adding

compile 'com.google.android.gms:play-services:7.8.0'

to my build.gradle I face the following errors, which should be only displayed if the libs are added twice.

G:\AndroidstudioProjects\SnapPref\app\src\main\res\values\colors.xml Error:(2) Attribute "adSize" has already been defined Error:(2) Attribute "adSizes" has already been defined Error:(2) Attribute "adUnitId" has already been defined Error:(2) Attribute "mapType" has already been defined Error:(2) Attribute "cameraBearing" has already been defined Error:(2) Attribute "cameraTargetLat" has already been defined Error:(2) Attribute "cameraTargetLng" has already been defined Error:(2) Attribute "cameraTilt" has already been defined Error:(2) Attribute "cameraZoom" has already been defined Error:(2) Attribute "uiCompass" has already been defined Error:(2) Attribute "uiRotateGestures" has already been defined Error:(2) Attribute "uiScrollGestures" has already been defined Error:(2) Attribute "uiTiltGestures" has already been defined Error:(2) Attribute "uiZoomControls" has already been defined Error:(2) Attribute "uiZoomGestures" has already been defined Error:(2) Attribute "useViewLifecycle" has already been defined Error:(2) Attribute "zOrderOnTop" has already been defined Error:(2) Attribute "environment" has already been defined Error:(2) Attribute "fragmentStyle" has already been defined Error:(2) Attribute "fragmentMode" has already been defined Error:(2) Attribute "buyButtonHeight" has already been defined Error:(2) Attribute "buyButtonWidth" has already been defined Error:(2) Attribute "buyButtonText" has already been defined Error:(2) Attribute "buyButtonAppearance" has already been defined Error:(2) Attribute "maskedWalletDetailsTextAppearance" has already been defined Error:(2) Attribute "maskedWalletDetailsHeaderTextAppearance" has already been defined Error:(2) Attribute "maskedWalletDetailsBackground" has already been defined Error:(2) Attribute "maskedWalletDetailsButtonTextAppearance" has already been defined Error:(2) Attribute "maskedWalletDetailsButtonBackground" has already been defined Error:(2) Attribute "maskedWalletDetailsLogoTextColor" has already been defined Error:(2) Attribute "maskedWalletDetailsLogoImageType" has already been defined G:\AndroidstudioProjects\SnapPref\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-wallet\7.8.0\res\values\wallet_styles.xml Error:(36, 43) String types not allowed (at 'buyButtonAppearance' with value 'google_wallet_classic').

My current build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"

    defaultConfig {
        applicationId "com.marz.snapprefs"
        minSdkVersion 11
        targetSdkVersion 21
        versionCode 13
        versionName "1.4.3 beta 4"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}
repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.android.gms:play-services:7.8.0'
    provided files('lib/XposedBridgeApi-54.jar')
    compile 'net.rdrei.android.dirchooser:library:2.1@aar'
    compile 'com.googlecode.mp4parser:isoparser:1.0.5.4'
}

My colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="background_gray_color">#fff5f5f5</color>
    <color name="common_action_bar_splitter">#ffd2d2d2</color>
    <color name="divider_grey">#ffefefef</color>
    <color name="header_divider">#ff999999</color>
    <color name="green">#00a650</color>
    <color name="white">#ffffffff</color>
    <color name="black">#ff000000</color>
    <color name="camera_activity_picture_text_message_background">#99000000</color>
    <color name="transparent">#000000</color>
    <color name="black_sixty_opacity">#99000000</color>
</resources>

I hope you guys have any suggestions, before this error gets me insane. Thanks in advance!



via Chebli Mohamed