So here's my situation I am working on MVC Patern. It's not any framework. It's just a basic setup of MVC done by myself. I am building a classifieds Ads Website. There are some categories and some sub-categories. DB columns are like:
id | name | parent

So, of course if the parent column is zero than the category is parent.
The problem is the function cat($id, $page). It takes $id and displays the related ads of that particular category id ($page is for pagination ). Now the url looks like this /ads/cat/1/1.
THE CODE:

public function cat($id=1, $page=1) 
{
    global $db;
    if ($id == '')
    {
        $id = 1;
    }
    $id = $db->escape($id);
    $page = $db->escape($page);


    $current_page = $page;
    $per_page = 10;
    $total_count = $db->get_var("SELECT COUNT(*) FROM ads WHERE category = {$id}");
    $pagination = new Pagination($current_page, $per_page, $total_count);

    $selected_category = $db->get_row("SELECT * FROM categories WHERE id = {$id}");
    $children = $db->get_results("SELECT * FROM categories WHERE parent = {$selected_category->id}");



    $results = $db->get_results("SELECT * FROM ads WHERE category = {$id} ORDER BY id DESC LIMIT {$per_page} OFFSET {$pagination->offset()}");
    $cats = $db->get_results("SELECT * FROM categories WHERE parent = 0");
    $cities = $db->get_results("SELECT * FROM cities");
    $this->render_view('std_header', array("page_title" => "Latest Ads || Find.pk", "cats"=> $cats));
    $this->render_view('category_view', array("all" => $results, "cats" => $cats, "cities" => $cities, "selected_category" => $selected_category, "pagination" => $pagination, "children" => $children));
    $this->render_view('std_footer', array("cat_id" => $id));
}

The problem comes in the view where I first loop through all of the categories and display them on the sidebar:

<ul>
    <?php foreach ($cats as $key): ?>
        <?php if ($selected_category->id == $key->id): ?>
            <li><span style="color: #428bca;" class="glyphicon glyphicon-ok"></span>&nbsp;&nbsp;
                <a href="<?php echo BASE_URL; ?>/ads/cat/<?php echo $key->id ?>"><?php echo $key->name; ?></a>
                <?php if ( !empty($children) ): ?>
                        <ul>
                            <?php foreach ($children as $child): ?>
                                <li>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="<?php echo BASE_URL; ?>/ads/cat/<?php echo $child->id ?>"><?php echo $child->name; ?></a></li>
                            <?php endforeach ?>
                        </ul>
                    </li>
                <?php else: ?>
                    </li>
                <?php endif; ?>
            </li>
        <?php else: ?>
            <li><a href="<?php echo BASE_URL; ?>/ads/cat/<?php echo $key->id ?>"><?php echo $key->name; ?></a></li>
        <?php endif; ?>

    <?php endforeach; ?>

</ul>

It shows a small tick mark depending on the current category. If the category has children categories it will make a sublist. But when I click on the subcategory the checkmark disappears with the children category however the the category is selected:

enter image description here

Take an example of this picture. When I click on the banking the banking category will be selected but the sub list would be gone along with the checkmark. Can anybody please suggest me a solution. I wasted a whole day on it and still I can't find any solution.

I'm trying to organize my software development projects folder, and for now I have 3 main categories of projects:

  1. Temporary, which I, for example, cloned from GitHub and not quite sure what to do with them
  2. Sandboxes, just some projects which I can always experiment with
  3. Rather serious ones.

The third category is obviously the most important for me, thus I don't want to create 3 folders (Temp, Sandboxes, Serious) inside my Dev folder, I'd better create folders "[Temp]", "[Sandboxes]", and folders for specific serious projects Like:

[Temp]
[Sandboxes]
SeriousProject1
SeriousProject2
etc.

Now I'm using square brackets to emphasize that the categories of folders WITH brackets are different from the categories of folders WITHOUT them. (here in brackets I have folders with a lot of somehow similar projects, and folders that contain a single project don't have brackets in their names)

It looks pretty good, but it's well known that symbols like brackets, spaces, hyphens etc. are not a great choice for dev folders (not ASCII, used natively by terminal etc.)

So my question is, what's the best choice in your opinion to emphasize folder category? (maybe smth like _Sandboxes or ???...)

I'd like to find out how do you guys handle the following situation: you have a class hierarchy, call it H1, with some polymorphic method that is supposed to accept an argument which type forms hierarchy H2 in the following way: the higher the class is in H1, the higher H2 argument it accepts.

+-----------+           +-----------+
|     A     |           |     A'    |
|-----------+           +-----------+
|method(A') |                 ^
+-----------+                 |
      ^                 +-----------+ 
      |                 |     B'    |
+-----------+           +-----------+
|     B     |                 ^
|-----------+                 |
|method(B') |           +-----------+ 
+-----------+           |     C'    |
      ^                 +-----------+
      |
+-----------+
|     C     |
|-----------+
|method(C') |
+-----------+

Before writing any code I mention that I have two protocol classes with methods check that have much in common, but request parameters are specific for concrete arguments -- transactions. The language is scala, but the problem is language-agnostic. At the first glance it should look like that:

trait BaseMerchantProtocol
{
  def check(transaction: BaseTransaction) = {
    // some common code...
    println(requestParams(transaction))
    // ...and here as well
  }

  protected def requestParams(transaction: BaseTransaction)
}

class SmsCommerceMerchantProtocol extends BaseMerchantProtocol
{
  override protected def requestParams(transaction: SmsCommerceTransaction) = {
    List("result specific for SmsCommerceTransaction class")
  }
}

class TelepayMerchantProtocol extends BaseMerchantProtocol
{
  override protected def requestParams(transaction: TelepayTransaction) = {
    List("result specific for TelepayTransaction class")
  }
}

But of course it does not compile as Liskov substitution principle is violated.

Let's try this one:

trait IMerchantProtocol {
  def check(transaction: SmsCommerceTransaction)
  def check(transaction: TelepayTransaction)
}

class MerchantProtocol extends IMerchantProtocol
{
  def check(transaction: SmsCommerceTransaction) = {
    doCheck(transaction)
  }

  def check(transaction: TelepayTransaction) = {
    doCheck(transaction)
  }

  private def requestParams(transaction: SmsCommerceTransaction) = {
    List("result specific for SmsCommerceTransaction class")
  }

  private def requestParams(transaction: TelepayTransaction) = {
    List("result specific for TelepayTransaction class")
  }

  private def doCheck(transaction: BaseTransaction) = {
    // some common code...
    println(requestParams(transaction))
    // ...and here as well
  }
}

But that won't compile as well -- and with the same reason: doCheck accepts BaseTransaction, but requestParamss have more strict preconditions.

The only thing that I came up with and that works is the following:

class MerchantProtocol extends IMerchantProtocol
{
  def check(transaction: SmsCommerceTransaction) = {
    doCheck(transaction, requestParams(transaction))
  }

  def check(transaction: TelepayTransaction) = {
    doCheck(transaction, requestParams(transaction))
  }

  private def requestParams(transaction: SmsCommerceTransaction) = {
    List("result specific for SmsCommerceTransaction class")
  }

  private def requestParams(transaction: TelepayTransaction) = {
    List("result specific for TelepayTransaction class")
  }

  private def doCheck(transaction: BaseTransaction, requestParams: List[String]) = {
    // some common code...
    println(requestParams)
    // ...and here as well
  }
}

But I don't like that all check methods belong to the same class. How can I split them by classes?

I used AndroidAnnotations in my Android project, my app performs requests to server in http. Now i need to use SSL on my api server. Is possible to perform requests to https server with AndroidAnnotations RestService?

Search operation is working fine and its searching the element in listview as well but problem is when I search some query, the view of gets updated based on query. How can i maintain the state in this scenario when checkbox is checked and unchecked ?

I have developed an app that plays a music when the user presses on button. And I have also developed a splash screen along with the app and it did work with the app. However, I want to modify my app so that splash screen plays gif file instead of regular image. When I tried .gif file by creating new project it did worked. I used movie class for that. I tried intent for my splash screen so that it calls gif.java file. But it did not worked. It just showed me the distorted image of my gif file. And than It said "Your APP HAS CRASHED". My main java, splash screen and gif .java files and manifest.xml are the following.

Main Java

import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;




    public class MainActivity extends Activity implements OnClickListener {
        private MediaPlayer mp;

       @Override
       public void onCreate(Bundle savedInstanceState) { 
           super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          setContentView(new MYGIFView (this));
          setVolumeControlStream(AudioManager.STREAM_MUSIC);
          findViewById(R.id.button_1).setOnClickListener(this);
          findViewById(R.id.button_2).setOnClickListener(this);
          findViewById(R.id.button_3).setOnClickListener(this);
       }
       public void onClick(View v) {   
           int resId=1;

       // Release any resources from previous MediaPlayer
          if (mp != null) {   
              mp.release(); 
          } 

          switch (v.getId()) {
          case R.id.button_1: resId = R.raw.button_1; break;
          case R.id.button_2: resId = R.raw.button_2; break;
          case R.id.button_3:
             startActivity(new Intent(MainActivity.this,SecondActivity.class));
             return;

          }

       // Create a new MediaPlayer to play this sound
          mp = MediaPlayer.create(this, resId); 
          mp.start();
       }
    }

Splash Screen. java

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

public class SplashScreen extends Activity {

    // Splash screen timer
    private static int SPLASH_TIME_OUT = 3000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        new Handler().postDelayed(new Runnable() {

            /*
             * Showing splash screen with a timer. This will be useful when you
             * want to show case your app logo / company
             */

            @Override
            public void run() {
                // This method will be executed once the timer is over
                // Start your app main activity
                Intent i = new Intent(SplashScreen.this, MYGIFView.class);
                startActivity(i);

                // close this activity
                finish();
            }
        }, SPLASH_TIME_OUT);
    }

}

MYGIF.java

import java.io.InputStream;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.view.View;

class MYGIFView extends View{

Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;
public MYGIFView(Context context) {
super(context);




is=context.getResources().openRawResource(R.drawable.th_welcome);
movie=Movie.decodeStream(is);

}

@Override
protected void onDraw(Canvas canvas) {

canvas.drawColor(Color.BLACK);
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;

}
System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
canvas.scale(3.50f, 3.50f);
movie.draw(canvas,20,20);
this.invalidate();
}
}

Manifest.xml

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="11" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >       
        <activity
            android:name=".SplashScreen"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <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=".SecondActivity" 
            android:label="@string/app_name"/>
    </application>

</manifest>

Logcat error

07-24 17:04:36.332: E/AndroidRuntime(580): FATAL EXCEPTION: main

07-24 17:04:36.332: E/AndroidRuntime(580): android.content.ActivityNotFoundException: Unable to find explicit activity class 

{.MYGIFView}; have you declared this activity in your AndroidManifest.xml?
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1508)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.app.Activity.startActivityForResult(Activity.java:3190)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.app.Activity.startActivity(Activity.java:3297)
07-24 17:04:36.332: E/AndroidRuntime(580):  at com.$1.run(SplashScreen.java:29)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.os.Handler.handleCallback(Handler.java:605)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.os.Looper.loop(Looper.java:137)
07-24 17:04:36.332: E/AndroidRuntime(580):  at android.app.ActivityThread.main(ActivityThread.java:4340)
07-24 17:04:36.332: E/AndroidRuntime(580):  at java.lang.reflect.Method.invokeNative(Native Method)
07-24 17:04:36.332: E/AndroidRuntime(580):  at java.lang.reflect.Method.invoke(Method.java:511)
07-24 17:04:36.332: E/AndroidRuntime(580):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-24 17:04:36.332: E/AndroidRuntime(580):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-24 17:04:36.332: E/AndroidRuntime(580):  at dalvik.system.NativeStart.main(Native Method)

Thanks in advance..

I want to create a customized ViewGroup which contains some ImageButtons rotated around one circle button.

enter image description here

Every ambient ImageButton was added to my viewgroup has the same layout position, which is on top and horizontal-center of viewgroup. After that, I will rotate each of them with specific angle, target is to create a ring around center button:

public class CustomeView extends ViewGroup {
private List<ArcButton> mArcButtons = new ArrayList<ArcButton>();

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    // ...
    mArcBtnBound = new RectF(0, 0, (mInnerRadius + mThickness), mThickness);
    mArcBtnBound.offsetTo(
            getPaddingLeft() + (mInnerRadius + mThickness) / 2,
            getPaddingTop());

    for(ArcButton arcBtn: mArcButtons) {
        arcBtn.layout(
                (int)mArcBtnBound.left,
                (int)mArcBtnBound.top,
                (int)mArcBtnBound.right,
                (int)mArcBtnBound.bottom);
    }
}
}

mInnerRadius is radius of center circle button, mThickness is height of ambient button in viewgroup. Adding an ambient ImageButton:

ArcButton btn = new ArcButton(getContext());
btn.setBackgroundResource(bkgResId);
btn.setImageResource(R.drawable.ic_launcher);
addView(btn);
btn.rotateTo(10, (mThickness + mInnerRadius) / 2, (mThickness + mInnerRadius));

I was reimplement draw() method of ImageButton class to rotate image view along with background, and provide a public method rotateTo.

public class ArcButton extends ImageButton {
private float mRotation;
private PointF mPivot;

@Override
public void draw(Canvas canvas) {
    canvas.save();
    canvas.rotate(mRotation, mPivot.x, mPivot.y);
    super.draw(canvas);
    canvas.restore();
}

public void rotateTo(float rotation, float pivotX, float pivotY) {
    mPivot.x = pivotX;
    mPivot.y = pivotY;
    mRotation = rotation;

    if (Build.VERSION.SDK_INT >= 11) {
        this.setPivotX(pivotX);
        this.setPivotY(pivotY);
        this.setRotation(rotation);
    } else {
        draw(new Canvas());
    }
}
}

As you can see the above screenshot, problem is my Imagebutton was cutoff. Can you help me to fix this?

Any other suggestions to rotate ambient buttons effectively are highly appreciated. Thank you so much!

how can i get all the visible childs from listview and apply on them(at a specific view) an effect?

Suppose we have this code:

@Override
public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount,
                     int totalItemCount) {

    for (int i = 0; i < absListView.getLastVisiblePosition()-firstVisibleItem; i++) {
        final View view = absListView.getChildAt(i);
        if (view != null) {

            //LOGIC HERE - Animation translate on this view

            MyCustomView mCustomView = (MyCustomView)view.findViewById(R.id.myview);
            mCustomView.foo();
        }
    }
}

Do i need an AsyncTask with WeakReference < T > or something to make this effect ?

So, I have a spinner set-up in my layout and I have implemented this code into the strings.xml:

 <string-array name="priority_array">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
</string-array>

I then put this code block into the onCreate():

 super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_activity_info);

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
            R.array.priority_array, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);

But, for some reason my app crashes and the log cat points to this line of code saying NullPointerException:

 spinner.setAdapter(adapter);

spinner1 is not null, adapter is not null, and spinner is not null, so I don't know what could be the problem. Yet, the app works completely fine when I comment out this one line of code, so I know this line has to do with my app crashing.

Here's the xml code snippet so everyone knows that spinner1 exist:

 <Spinner
    android:id="@+id/spinner1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView1"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="36dp" />

LogCat:

07-24 13:52:07.728: D/ActivityThread(24892): setTargetHeapUtilization:0.25
07-24 13:52:07.728: D/ActivityThread(24892): setTargetHeapIdealFree:8388608
07-24 13:52:07.728: D/ActivityThread(24892): setTargetHeapConcurrentStart:2097152
07-24 13:52:08.108: D/AbsListView(24892): Get MotionRecognitionManager
07-24 13:52:08.659: I/Adreno200-EGLSUB(24892): <ConfigWindowMatch:2136>: Format     RGBA_8888.
07-24 13:52:08.709: E/(24892): <s3dReadConfigFile:75>: Can't open file for reading
07-24 13:52:08.709: E/(24892): <s3dReadConfigFile:75>: Can't open file for reading
07-24 13:52:10.781: D/AbsListView(24892): Get MotionRecognitionManager
07-24 13:52:10.921: I/Adreno200-EGLSUB(24892): <ConfigWindowMatch:2136>: Format     RGBA_8888.
07-24 13:52:11.122: E/SpannableStringBuilder(24892): SPAN_EXCLUSIVE_EXCLUSIVE spans     cannot have a zero length
07-24 13:52:11.122: E/SpannableStringBuilder(24892): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
07-24 13:52:13.254: W/dalvikvm(24892): threadid=1: thread exiting with uncaught   exception (group=0x41bf4438)
07-24 13:52:13.264: E/AndroidRuntime(24892): FATAL EXCEPTION: main
07-24 13:52:13.264: E/AndroidRuntime(24892): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.daymanager/com.example.daymanager.ActivityInfo}: java.lang.NullPointerException
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.ActivityThread.access$700(ActivityThread.java:143)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.os.Looper.loop(Looper.java:137)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.ActivityThread.main(ActivityThread.java:4953)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at java.lang.reflect.Method.invokeNative(Native Method)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at java.lang.reflect.Method.invoke(Method.java:511)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at dalvik.system.NativeStart.main(Native Method)
07-24 13:52:13.264: E/AndroidRuntime(24892): Caused by: java.lang.NullPointerException
07-24 13:52:13.264: E/AndroidRuntime(24892):    at com.example.daymanager.ActivityInfo.onCreate(ActivityInfo.java:31)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.Activity.performCreate(Activity.java:5160)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
07-24 13:52:13.264: E/AndroidRuntime(24892):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
07-24 13:52:13.264: E/AndroidRuntime(24892):    ... 11 more

http://REST-SERVICE/Requests.svc/[ID]/media/

HTTP Method: POST

Request, Unknown format, The request body is a byte stream.

How would I go about posting an image to the server using this particular request in Android?

I've tried to convert the image to a byte array:

> byte[] imageByte = stream.toByteArray();
> 
> httpPost.setEntity(new ByteArrayEntity(imageByte));
> httpClient.execute(httpPost);

This doesn't work and just returns a (400) Bad Request error.

Any help is appreciated.

so im running an app on android 2.3.3 which is inserting a row to a sqlite db.

This is how I add the row:

public static void addAlert(String inId, String inDate, String inLat,
            String inLng, String inAddress, String inComment)
    {
        Log.d("general", "adding alert to local list:");

        inAddress = inAddress.replace("null", ""); // remove null

        ContentValues insertValues = new ContentValues();
        insertValues.put(ID, inId);
        insertValues.put(DATE, inDate);
        insertValues.put(LAT, inLat);
        insertValues.put(LNG, inLng);
        insertValues.put(ADR, inAddress);
        insertValues.put(COMMENT, inComment);

        Log.d("general", "" + db.insert(ALERT_TABLE_NAME, null, insertValues));
    }

Why does this not add a row to the local sqlite db?

The db.insert( ... ); always returns 12 and no errors are given.

I am using GoogleCloudMessaging API for Push Notification. I get the success from PHP side but not receive push notification in android device. I received the following as a response from PHP side,

'{"multicast_id":8498502225166328169,"success":1,"failure":0,"canonical_ids":1,"results":[{"registration_id":"xxxxxxxxxxxxxxx","message_id":"0:1393854840250166%eee44707f9fd7ecd"}]}' (length=326)

My Broadcast Receiver:

public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Explicitly specify that GcmIntentService will handle the intent.
    ComponentName comp = new ComponentName(context.getPackageName(),
            GcmIntentService.class.getName());
    // Start the service, keeping the device awake while it is launching.
    startWakefulService(context, (intent.setComponent(comp)));
    setResultCode(Activity.RESULT_OK);
}

}

My GcmIntentService:

public class GcmIntentService extends IntentService {
Context context;
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public static final String TAG = "GCM Demo";

public GcmIntentService() {
    super("GcmIntentService");
    // TODO Auto-generated constructor stub
}

@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    Bundle extras = intent.getExtras();
    String msg = intent.getStringExtra("message");
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);

    if (!extras.isEmpty()) {

        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                .equals(messageType)) {
            sendNotification("Send error: " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                .equals(messageType)) {
            sendNotification("Deleted messages on server: "
                    + extras.toString());
            // If it's a regular GCM message, do some work.
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                .equals(messageType)) {
            // This loop represents the service doing some work.
            for (int i = 0; i < 5; i++) {
                Log.i(TAG,
                        "Working... " + (i + 1) + "/5 @ "
                                + SystemClock.elapsedRealtime());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                }
            }
            Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
            // Post notification of received message.
            // sendNotification("Received: " + extras.toString());
            sendNotification(msg);
            Log.i(TAG, "Received: " + extras.toString());
        }
    }
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}

private void sendNotification(String msg) {
    mNotificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);

    Intent myintent = new Intent(this, NotificationReceiveActivity.class);
    myintent.putExtra("message", msg);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            myintent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            this).setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("GCM Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
            .setContentText(msg);

    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}

}

manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.myapp.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />

<permission
    android:name="com.myapp.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen" >
    <activity
        android:name=".SplashActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <activity
        android:name=".NotificationReceiveActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="stateHidden" >
    </activity>

    <receiver
        android:name=".GcmBroadcastReceiver"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <category android:name="com.myapp" />
        </intent-filter>
    </receiver>

    <service android:name=".GCMIntentService" />

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

Help me! Thanks in Adavnce

I'm developing a android app cappable of acessing the maps API, but i'm stuck on error:

Google Maps Android API´╣Ľ Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).

Already did the key and activate everithing in google API console.

These are my files:

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="hflopes.mapas" >

    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"></uses-permission>

    <uses-feature android:glEsVersion="0x00020000"
        android:required="true"></uses-feature>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBTObQnY1mxYwXw1g8txH5ApBu8ovxv730" />
        <activity android:name=".MostraAlunosProximos"></activity>
        <activity
            android:name=".mapas"
            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>

mapas_layout:

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/mapa"/>


</LinearLayout>

Class for Loading the map:

package hflopes.mapas;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by HFLopes on 24/07/2014.
 */
public class MostraAlunosProximos extends FragmentActivity{

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

        FragmentManager manager = getSupportFragmentManager();

        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.mapa, new MapaFragment());
        transaction.commit();

    }
}

Any Idea?

Thanks for the help

I have an app that lets the user log in through Facebook SDK. This works fine. I am trying to display that user's profile picture on a welcome activity along with their name. I can successfully get their name and display it, but I get a null pointer when I try to get their profile picture. This is the code snippet:

if (user != null) {
    TextView welcome = (TextView) findViewById(R.id.textView2);
    welcome.setText(user.getName());
    ProfilePictureView userPicture = (ProfilePictureView) findViewById(R.id.imageView1);
    userPicture.setProfileId(user.getId());
}

I am successfully retrieving and displaying the user's name by using welcome.setText(user.getName()); so I know that the user != null. And the error is on this line: userPicture.setProfileId(user.getId()); Any ideas? Thanks.

Full Code

public class WelcomeScreen extends ActionBarActivity {

TextView tv;

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

    tv = (TextView) findViewById(R.id.textView1);
    // Session session = Session.getActiveSession();
    if (Session.getActiveSession() != null) {
        Log.d("In?", String.valueOf(Session.getActiveSession().isOpened()));
    } else {
        Log.d("Session is ", "null");
    }

    if (Session.getActiveSession() != null
            || !Session.getActiveSession().isClosed()) {
        Session.openActiveSession(WelcomeScreen.this, true,
                new Session.StatusCallback() {

                    // callback when session changes state
                    @Override
                    public void call(Session session, SessionState state,
                            Exception exception) {
                        if (session.isOpened()) {

                            // make request to the /me API
                            Request.newMeRequest(session,
                                    new Request.GraphUserCallback() {

                                        // callback after Graph API
                                        // response with user
                                        // object
                                        @Override
                                        public void onCompleted(
                                                GraphUser user,
                                                Response response) {
                                            if (user != null) {
                                                TextView welcome = (TextView) findViewById(R.id.textView2);
                                                welcome.setText(user
                                                        .getName());
                                                ProfilePictureView userPicture = (ProfilePictureView) findViewById(R.id.imageView1);
                                                userPicture.setProfileId(user.getId());
                                            }
                                        }
                                    }).executeAsync();
                            Log.d("In?", String.valueOf(Session
                                    .getActiveSession().isOpened()));
                            session = Session.getActiveSession();
                            if (session == null) {
                                Log.d("Session is", "null");
                            }
                        }
                    }
                });
    }

}

}

Logcat

07-24 13:44:15.061: E/AndroidRuntime(10953): FATAL EXCEPTION: main
07-24 13:44:15.061: E/AndroidRuntime(10953): java.lang.NullPointerException
07-24 13:44:15.061: E/AndroidRuntime(10953):    at com.example.test.WelcomeScreen$1$1.onCompleted(WelcomeScreen.java:79)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at com.facebook.Request$1.onCompleted(Request.java:303)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at com.facebook.Request$4.run(Request.java:1726)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at android.os.Handler.handleCallback(Handler.java:730)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at android.os.Looper.loop(Looper.java:137)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at android.app.ActivityThread.main(ActivityThread.java:5289)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at java.lang.reflect.Method.invokeNative(Native Method)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at java.lang.reflect.Method.invoke(Method.java:525)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
07-24 13:44:15.061: E/AndroidRuntime(10953):    at dalvik.system.NativeStart.main(Native Method)

EDIT

I've been looking around and I think I might need to request permission to access the user's photos? If this is the case, any ideas how I can? Thanks.

Most books, online resources, and Android IDEs suggest to store xml resource files according to their type, e.g. in Android Studio:

/values
    dimens.xml
    strings.xml
    colors.xml
    ...

I can see the value in this if you want to reuse resources for multiple activities (e.g. colors). However, what if you want to store all of the data for a particular activity? I find it useful to have them grouped together. If reuse is a concern why not define reusable resource grouped by type, and use a reference to it in your activity.xml?

Is grouping resources -- with mixed types -- by activity a bad practice? Why is it never suggested? Is there some down side?

I'm trying to parse a json and return its values in an array, then I want to show it in a listview, the log shows me the result that I want, but it is not showing in my cellphone, I'm missing something that I don't know.

The function that make the SyncTask:

   public class SincronizarTask {
    private Activity ctx;
    public SincronizarTask(Activity applicationContext) {
        this.ctx = applicationContext;
    }

    public void inicia(){
        this.syncClientes();
    }

    private void syncClientes() {
        ClientRest mClientesRest = new ClientRest(ctx);
        mClientesRest.getClientes(new ClientRest.ClientesRestListener() {
            public void clientesReceived(List<ClientesModel> clientes) {
                for (int i = 0; i < clientes.size(); i++) {
                    System.out.println(clientes.get(i).getNome());
                }
            }
        });
    }
}

ClienteActivity:

public class ClienteActivity extends SherlockFragment {
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cliente, container, false);
        try {
            ClienteViewAdapter ad = new ClienteViewAdapter(this.getActivity(), R.layout.fragment_cliente_item);
            ListView lv = (ListView) view.findViewById(R.id.listaClientes);

            lv.setVerticalFadingEdgeEnabled(true);
            lv.setVerticalScrollBarEnabled(true);

            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                   // TextView clienteId = (TextView) view.findViewById(R.id.clienteId);
                    TextView clienteNome = (TextView) view.findViewById(R.id.clienteNome);
                    TextView clienteTipoPessoa = (TextView) view.findViewById(R.id.clienteTipo);

                    Intent intent = new Intent(getActivity(), ContatosView.class);
                    //intent.putExtra("id_cliente", clienteId.getText()); // envia o id do cliente para a tela de detalhes
                    intent.putExtra("nome", clienteNome.getText());
                    intent.putExtra("tipo_pessoa", clienteTipoPessoa.getText());

                    startActivity(intent);
                }
            });

            lv.setAdapter(ad);
        } catch (Exception e) {
            new AlertDialog.Builder(getActivity()).setTitle("Erro").setMessage(e.getMessage()).setNeutralButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            }).show();
        }
        return view;
    }

ClienteViewAdapter:

public class ClienteViewAdapter extends ArrayAdapter<ClientesModel> {
    private final LayoutInflater inflater;
    private final int resourceId;

    public ClienteViewAdapter(FragmentActivity context, int resource) {
        super(context, resource);
        this.inflater = LayoutInflater.from(context);
        this.resourceId = resource;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {
        ClientesModel cliente = getItem(position);

        view = inflater.inflate(resourceId, parent, false);

        //TextView tvId = (TextView) view.findViewById(R.id.txtTitle);
        TextView tvNome = (TextView) view.findViewById(R.id.clienteNome);
        TextView tvTipo = (TextView) view.findViewById(R.id.clienteTipo);

        //tvId.setText(String.valueOf(cliente.ge()));
        tvNome.setText(cliente.getNome());
        tvTipo.setText(cliente.getTipo_pessoa());

        return view;
    }
}

ClientRest:

        JsonObjectRequest mJsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                List<ClientesModel> clientes = null;
                try {
                    clientes = parseJSON(response);
                    pDialog.hide();
                } catch (JSONException e) {
                    e.printStackTrace();

                }
                listener.clientesReceived(clientes);
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (pDialog.isShowing()) {
                    pDialog.hide();
                }
                error.printStackTrace();
            }

        }
        ) 

        mRequestQueue.add(mJsonObjectRequest);
    }

    private List<ClientesModel> parseJSON(JSONObject json) throws JSONException {
        try {
            JSONArray dados = json.getJSONArray("dados");

            for (int i = 0; i < dados.length(); i++) {
                JSONObject item = dados.getJSONObject(i);

                ClientesModel mClientesModel = new ClientesModel();
                ClientesContatosModel mClientesContatoModel = new ClientesContatosModel();

                /* cadastra os dados necessários no objeto no modelo */
                mClientesModel.setId(item.optInt("id"));
                mClientesModel.setNome(item.optString("nome"));
                mClientesModel.setTipo_pessoa(item.optString("tipo_pessoa"));
                mClientesModel.setInformacoes_adicionais(item.optString("informacoes_adicionais"));
                mClientesModel.setCpf(item.optString("cpf"));
                mClientesModel.setCnpj(item.optString("cnpj"));
                JSONArray contatos = item.getJSONArray("contatos");
                for (int j = 0; j < contatos.length(); j++) {
                    JSONObject data = contatos.getJSONObject(j);

                    mClientesContatoModel.setNome(data.optString("nome"));

                    mClientesContatoModel.setCargo(data.optString("cargo"));

                }

                arrNews.add(mClientesModel);
                arrContatos.add(mClientesContatoModel);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return arrNews;
    }
}

is there any free web service which also provide a database? I am thinking for an application which hits a free web service and fetch and save some data. Is there any kind of free web services to save my data and retrieve data when ever required from android. I visited Google cloud storage and API, but it doesn't look heavy for integration. Can any one suggest me some easiest things?

I have this application that is visible in the Gallery build in android application. When I selected multiple images and press via "Share Application"/ The application I'm developing, the application starts and all the images selected are displayed in view pager to swipe between them.

On each page, I have an imageview, text view and edit text. The imageview to display the image. The text view to set the date (using date picker) and edit text to set the title.

The problem is when i set the date or title on a certain and swipe to the next then re-swipe back the information i set is erased.

i want the information to be saved not wiped or edited due to a change on the next pages.

how can I do that? I have the codes if anyone would like to see.

I'm very experienced on Unity and iOS and I can deploy my Unity app to Android. But I don't know anything about native Android stuff.

My problem is about receiving a GCM message and showing a notification when the android app is in background. I implemented it and it works perfect when the app is in foreground but my GCM message listener isn't being triggered when the app is in background and I can't show the notification.

I use this plugin for receiving GCM messages : https://github.com/kskkbys/unity-gcm I use this for showing the notification : https://www.assetstore.unity3d.com/en/#!/content/9484

I tried to reach out the authors of these plugins but they didn't reply for a long time...

I've successfully implemented Android In-app Billing in a Cocos2d-x 2.0 Android app. Now, I'm trying to implement Android In-app Billing in a Cocos2d-x 3.0 Android app. Some of the techniques I used before are not working. I want to understand the cause of the problems.

Specifically, I'm having trouble calling Java methods. The "C++ to Java" JNI part is working. The IAB method in AppActivity.java is successfully called from C++:

public static void IAB(String s) {
    instance.doIAB(s);
}

The trouble starts with instance. I'm not a Java programmer, so this is probably ugly. I'm using instance to call non-static methods from my static IAB method. instance is set in onCreate after the call to super.onCreate:

instance = this;

Also, I have this declaration inside AppActivity:

private static AppActivity instance;

This worked in Cocos2d-x 2.0. However, now I'm just receiving a crash on the line:

instance.doIAB(s);

Ideally, I can run my app in the IDE and see errors in the log. However, Eclipse + Cocos2d-x 3.0 doesn't want to run my app from the IDE. So I'm just using the Cocos2d-x 3.0 command line way of running the Android app. This is limiting my understanding of the crash.

How can I understand and fix this issue?

I am using this code to capture sound data of my device,but how do I stop these functions from further capturing the data, nothing seems to work, the app gets stuck in a particular state.

    Visualizer mVisualizer = new Visualizer(0);
    mVisualizer.setEnabled(false);
    int capRate = Visualizer.getMaxCaptureRate();
    int capSize = Visualizer.getCaptureSizeRange()[1];
    mVisualizer.setCaptureSize(capSize);
    Visualizer.OnDataCaptureListener captureListener = new Visualizer.OnDataCaptureListener() {
        @Override
        public void onWaveFormDataCapture(Visualizer visualizer,
                byte[] bytes, int samplingRate) {

            Camera cam = Camera.open();
            Parameters params;
            int length = bytes.length;
            for (int i = 0; i < length; i++) {
                Log.d("neela", "peela");


                if (bytes[i] > 90 || bytes[i] <= -90) {
                    Log.d("hehe", "pepe");
                    params = cam.getParameters();
                    params.setFlashMode(Parameters.FLASH_MODE_OFF);
                    cam.setParameters(params);
                    cam.stopPreview();

                } else {

                    params = cam.getParameters();
                    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
                    cam.setParameters(params);
                    cam.startPreview();
                    Log.d("check", "control");
                }

            }
            if (cam != null) {
                cam.stopPreview();
                cam.release();
                cam = null;
            }

}

        @Override
        public void onFftDataCapture(Visualizer visualizer, byte[] bytes,
                int samplingRate) {
        }

    };

    int status = mVisualizer.setDataCaptureListener(captureListener,
            capRate, true/* wave */, false/* no fft needed */);
    mVisualizer.setEnabled(true);

}

The above code is the code for turnOnFlash() and works fine, but when I call the method turnOffFlash() nothing seems to work and app remains in the same state

    btnSwitch.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isFlashOn) {
                // turn off flash
                turnOffFlash();
            } else {
                // turn on flash
                turnOnFlash();
            }
        }
    });