I am currently trying to implement a custom keyboard that sends an image (possibly via an intent?) to a certain application. More specifically, I am trying to I am trying to create a key on a custom keyboard that would send an image to the default messaging app so that it can be sent as an MMS.

I have modified the sample SoftKeyboard project in order to do this. Here is what I have so far:

private void handleCharacter(int primaryCode, int[] keyCodes) {
    if (isInputViewShown()) {
        if (mInputView.isShifted()) {
            primaryCode = Character.toUpperCase(primaryCode);
        }
    }
    if (isAlphabet(primaryCode) && mPredictionOn) {
        mComposing.append((char) primaryCode);

        // Send message here
        Intent pictureMessageIntent = new Intent(Intent.ACTION_SEND);
        pictureMessageIntent.setType("image/png");
        Uri uri = Uri.parse("android.resource://" + this.getPackageName() + "/drawable/icon_en_gb");
        pictureMessageIntent.putExtra(Intent.EXTRA_STREAM, uri);
        startActivity(pictureMessageIntent);

        getCurrentInputConnection().setComposingText(mComposing, 1);
        updateShiftKeyState(getCurrentInputEditorInfo());
        updateCandidates();
    } else {
        getCurrentInputConnection().commitText(
                String.valueOf((char) primaryCode), 1);
    }
}

The problem is I am getting a runtime exception that says:

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

I'm unfamiliar with Android custom keyboards, but I'm not sure if starting a new Activity is the best idea. Does anyone have any suggestions?

I have an Android application with webview. there are two pages with an iframe that shows pdf using google docs. My problem is that loading this: javascript:document.getElementsByTagName(\"iframe\")[0].src = document.getElementsByTagName(\"iframe\")[0].src; works only for one of those pages. The strange thing is that there is no problem if I other url when changing the src (for example a picture). What could be the problem?

I have data that I present as TableLayout. I want to implement paging as data are many and cannot fit single device (no so many though). I want to show next table when user swipes the UI. is there Android widget that can do that? I have searched google and StackOverflow to no avail. Android Manual is not that helpful to me either.

any help or direction is appreciated

I am trying to record from the video camera in my application. I have removed try/catch blocks and things of that nature to show an example of how to record:

camera.unlock();
mediaRecorder.setCamera(camera);
mediaRecorder.reset();
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);

CamcorderProfile mCamcorderProfile = CamcorderProfile.get(CameraInfo.CAMERA_FACING_FRONT, CamcorderProfile.QUALITY_720P);
mediaRecorder.setProfile(mCamcorderProfile);

/*      
mediaRecorder.setVideoEncodingBitRate(8000000);
mediaRecorder.setVideoEncodingBitRate(5000000);
mediaRecorder.setVideoEncodingBitRate(3000000);
*/

mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mRecFile = File.createTempFile("Video", ".mp4", mRecVideoPath);
mediaRecorder.setOutputFile(mRecFile.getAbsolutePath());
mediaRecorder.prepare();
mediaRecorder.start();

I record the video and it plays perfectly on the phone. Then I pull the video file off and I play it on a PC and the audio/video is slightly out of sync on a short 10 second clip. This only happens when recorded with a Samsung Note 3.

Just to be thorough, here is what I have tried:

  • Works perfectly on a Nexus 7

  • Works perfectly on a Samsung S3

  • Tried recording on two different Note 3

  • Tried various bitrates

For playing the out of sync video from the Note 3:

  • Played video on a Macbook pro, Chrome browser

  • Played video on a Macbook pro, quicktime

  • Played video on a Win7 pc

Out of sync on all of them.

When recording a video on the Note 3 with the stock camera app there is NO sync issue!

I am creating an off-canvas navigation menu and have found an issue on two Nexus devices, on Chrome only. I am using the latest version.

Elements which have click events assigned to them, including native anchor tags, respond to touches outside of their confines, by what feels like 5–10px.

Is there any information about this behaviour and is there anyway to prevent it?

I am a beginner working with graphics. Right now I have an image displayed in random places on the screen. What I would like to do that if the image is touched, it should be replaced by another image. How can I do that? Another thing I currently am using a class within a class.Thanks

public class MainActivity extends ActionBarActivity implements OnTouchListener{

MyGameGraphics myGraphics;
TextView tvScore, tvPlayerScore;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    tvScore = (TextView)findViewById(R.id.showScore);
    tvPlayerScore = (TextView)findViewById(R.id.playerScore);

    myGraphics = new GraphicsMain(this);

    myGraphics.setOnTouchListener(this);

    setContentView(myGraphics);




    }

@Override
protected void onPause(){

    super.onPause();
    myGraphics.pause();


}

@Override
protected void onResume(){

    super.onResume();
    myGraphics.resume();
}






@Override
public boolean onTouch(View arg0, MotionEvent event) {
    // TODO Auto-generated method stub

    // How to change image using touch event here?

    return false;

}





public class MyGameGraphics extends SurfaceView implements Runnable {

    SurfaceHolder ourHolder;
    Thread ourThread = null;
    Boolean isRunning = false;
    int[] images = new int[]{R.drawable.image1, R.drawable.image2};





    public MyGameGraphics(Context context) {

        super(context);
        ourHolder = getHolder();

    }

      public void pause(){

          isRunning = false;
          while(true){

              try {


                ourThread.join();


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


            }

             break; 
          }
          ourThread = null;

      }

      public void resume(){

          isRunning = true;
          ourThread = new Thread(this);
          ourThread.start();

      }


    @Override
    public void run() {



        while(isRunning){

            if(!ourHolder.getSurface().isValid())
             continue;

            Canvas ourCanvas = ourHolder.lockCanvas();
            ourCanvas.drawRGB(0, 0, 0);


            Random rn = new Random();
            int location = rn.nextInt(12);

            for(int i = 0; i < 500; i++){

                try {

            Random rn2 = new Random();
            int generateWidthLocation = rn2.nextInt(420);
            int generateHeightLocation = rn2.nextInt(600);


            Bitmap btmp = BitmapFactory.decodeResource(getResources(), images[location]);
            ourCanvas.drawBitmap(btmp, generateWidthLocation, generateHeightLocation,  null);

                ourThread.sleep(3000);




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






            ourHolder.unlockCanvasAndPost(ourCanvas);

        }



             }

}

}

I am in the process of writing an app for an android tablet to communicate to an aurduino via bluetooth. I am using kivy and this bluetooth demo code: https://gist.github.com/tito/7432757

I have managed to connect to the aurduino and send data, but now i need a method of seeing the messages that are being sent back and fourth (preferably in real time). This post says there is a debugger built into android 4.4, but the output is not real time: Sniffing/logging your own Android Bluetooth traffic

I have downloaded a variety of bluetooth spp and terminal apps but none seem to be able to connect when any other one is connected (example bluetooth terminal and a simple bluetooth chat app). Does anyone know of an app that can do this? This post mentions "hcidump" but i cannot get that to work either: How to sniff Bluetooth traffic in Android?

Im open to using a pc to interface too. I set up a comm port for bluetooth, but it seems putty wont show anything until there is a connection and bluetooth wont connect until there is something to connect to; catch22. Even just an emulator that posts every message it receives to it to the screen would be very helpful. Thanks for your help guys!

You usually traverse a list by scrolling through the views that are placed one after another. What I'm trying to achieve is similar, but the views would be stacked on top of each other. The views will also cover the whole screen. So when you scroll, the top view slides away (or uses some other transition animation), but the bottom one is not moving underneath. You can imagine that the views are like the papers in a top spiral-bound notebook.

So my question is - does something similar already exist? I haven't been able to found anything so I might need to make a custom implementation. Oh and the views will each contain an image and there might be quite a few of them, so it will need to handle that (I was thinking of using Android Universal Image Loader). Thanks.

I have a horizontal scroll view that takes up the right half of the screen. On it, I have an EditText. When I select the EditText to edit the text, the HorizontalScrollView scrolls to the right. I'm guessing it's trying to place the EditText to the leftmost position. Regardless, since the HorizontalScrollView takes up the rightside of the screen, by doing this, I can no longer see the EditText since its now covered up by the contents I put on the left side of the screen. How can I prevent HorizontalScrollView from automatically scrolling when I focus on something inside its layout?

Thanks. Much appreciated.

Edit: Posting code. I'm actually creating my EditText's based off of generated info, so this is not what it actually looks like, but it should capture jist of it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <View
        android:layout_leftOf="@+id/Anchor"/>


    <View
        android:id="@+id/Anchor"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerHorizontal="true"
        android:background="#000" />

    <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_rightOf="@+id/Anchor"
            android:fillViewport="true" >

            <HorizontalScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fillViewport="true" >

                <TableLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="10dp" >

                  <TableRow>
                     <EditText>

                     ABOVE is the view that is going to the left

                     MOre views which would cause Scrolling to the right

                  </TableRow>
                </TableLayout>

            </HorizontalScrollView>
        </ScrollView>

</RelativeLayout>

In my onCreate, I have the code:

    interstitial = new InterstitialAd(this);
    interstitial.setAdUnitId("ca-app-pub-1852329945819279/4025192744");

    // Create ad request.
    AdRequest adRequest1 = new AdRequest.Builder().build();

    // Begin loading your interstitial.
    interstitial.loadAd(adRequest1);  

Where "interstitial" is a private InterstitialAd interstitial.

I then display the interstitial using the following method:

public void displayInterstitial() {

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (interstitial.isLoaded()) {
                interstitial.show();
            }
            resetInterstitial();
        }
    });

}  

How can I display the interstitial (call the displayInterstitial() method) as soon as the interstitial is loaded? All help appreciated.

I always use match_parent or wrap_content in width and/or height and I work with margin and padding (depending I use 0dp on height when I use weight of Linear Layout) to adjust my layout depending on my needs.

I read that is the correct way to work if I am developing for any size of android screens.

Is there any situation that is better to use fixed size in android layout?

I have 1 function to print the text of the button, and i use that function for the 3 button, how do i know in what button the user click? (sorry but my english is low) Example:

        public void function(View view) {
        TextView text = (TextView) findViewById(R.id.textView);
        Button button1= (Button) findViewById(R.id.button3);
        Button button1= (Button) findViewById(R.id.button4);
        Button button1= (Button) findViewById(R.id.button5);

        text.setText(button <?> .getText()); }

is the number of the button the user click

Its any way to know in which button the user click? Please help, Thanks.

my aim is to have an activity that can be like a bag for the player. i use the database to store the object and i want to have the possibility to do some thing with then from the bag. i want to make them clickable, and to have a dialog with the options of what the player can do of them. the 4 buttons in dialog have to be able to: delete the clicked object form the database (already got it), dismiss the dialog (already got it), and to use and show info about the object clicked. the problem is that i can't identify the clicked items. how can i do it? and how can i change prefs for the different clicked items?

public class TestDatabaseActivity extends ListActivity implements
    OnClickListener {
private ItemsDataSource datasource;
TextView dt;
SharedPreferences prefs;
String str;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final ListView list = (ListView) findViewById(R.id.list);datasource = new ItemsDataSource(this);
    datasource.open();

    List<Item> values = datasource.getAllItems();

    prefs = getSharedPreferences("com.eightynineindustries.librogamebase",MODE_PRIVATE);
    String sel=prefs.getString("sel",null);

    Toast.makeText(this, ""+sel, Toast.LENGTH_LONG).show(); 

    // use the SimpleCursorAdapter to show the
    // elements in a ListView
    ArrayAdapter<Item> adapter = new ArrayAdapter<Item>(this,
            android.R.layout.simple_list_item_1, values);
    setListAdapter(adapter);


      }

// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
    @SuppressWarnings("unchecked")
    ArrayAdapter<Item> adapter = (ArrayAdapter<Item>) getListAdapter();
    Item item = null;
    switch (view.getId()) {
    case R.id.add:
        String[] items = new String[] { "pozione", "lettera", "spada",
                "cavallo" };
        int nextInt = new Random().nextInt(4);
        // save the new comment to the database
        item = datasource.createItem(items[nextInt]);
        adapter.add(item);
        break;
    case R.id.delete:
        if (getListAdapter().getCount() > 0) {
            item = (Item) getListAdapter().getItem(0);
            datasource.deleteItem(item);
            adapter.remove(item);
        }
        break;
    case R.id.pane:



        break;
    }
    adapter.notifyDataSetChanged();
}

@Override
protected void onResume() {
    datasource.open();
    super.onResume();
}

@Override
protected void onPause() {
    datasource.close();
    super.onPause();
}

@Override
protected void onListItemClick(  final ListView list, View v, final int position,
        long id) {

    prefs = getSharedPreferences("com.eightynineindustries.librogamebase",MODE_PRIVATE);
//  str =  (String) list.getItemAtPosition(position);

    // TODO Auto-generated method stub
    super.onListItemClick(list, v, position, id);

    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.dialog);
    dialog.setTitle("Oggetto selezionato");



    Button button1 = (Button) dialog.findViewById(R.id.button1);
    Button button2 = (Button) dialog.findViewById(R.id.button2);
    Button button3 = (Button) dialog.findViewById(R.id.button3);
    Button button4 = (Button) dialog.findViewById(R.id.button4);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
    button3.setOnClickListener(this);
    button4.setOnClickListener(this);



    button1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View d) {
            // do something to change prefs and then delete the item

            @SuppressWarnings("unchecked")
            ArrayAdapter<Item> adapter = (ArrayAdapter<Item>) getListAdapter();
            Item item = null;

            str = (String) getListView().getItemAtPosition(position);



            if ( str == "cavallo") {
                prefs.edit().putString("sel", "cavallo").commit();
            } else if (str == "lettera" ) {
                prefs.edit().putString("sel", "lettera").commit();
            } else if (str == "spada") {
                prefs.edit().putString("sel", "spada").commit();
            } else if (str == "pozione") {
                prefs.edit().putString("sel", "pozione").commit();
            } else {
                prefs.edit().putString("sel", "cacchiolo").commit();
            }
            item = (Item) getListView().getItemAtPosition(position);
            datasource.deleteItem(item);
            adapter.remove(item);

            dialog.dismiss();
        }
    });
    button2.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            // do something to delete selected item

            @SuppressWarnings("unchecked")
            ArrayAdapter<Item> adapter = (ArrayAdapter<Item>) getListAdapter();
            Item item = null;
            item = (Item) getListView().getItemAtPosition(position);
            datasource.deleteItem(item);
            adapter.remove(item);

            dialog.dismiss();
        }
    });
    button3.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    button4.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });

    dialog.show();
}}

all i get till this moment is that every time i press the first button to use the item and delete it, the shared prefs changes to "cacchiolo", every item i press. how can i solve it?

I`am developping and android VoIP apps using Audiotracks and Audiorecord. But there is a lot of echo, I tried to use Speex echo canceller with JNI but I get error :

07-21 16:58:39.029: A/libc(7570): Fatal signal 11 (SIGSEGV) at 0x00000008 (code=1)

the important of my code is

   public void run(){

      short[] audioShorts, recvShorts, recordedShorts, filteredShorts;
      byte[] audioBytes, recvBytes;
      int shortsRead;
      DatagramPacket packet;

      int samplingRate = 8000;
      int managerBufferSize = 2000;
      AudioTrack player = new AudioTrack(AudioManager.STREAM_MUSIC, samplingRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, managerBufferSize, AudioTrack.MODE_STREAM);
      recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, samplingRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, managerBufferSize);
      recorder.startRecording();
      player.play();

      audioShorts = new short[1000];
      shortsRead = recorder.read(audioShorts, 0, audioShorts.length);

      audioBytes = new byte[shortsRead*2];
      ByteBuffer.wrap(audioBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(audioShorts);

      packet = new DatagramPacket(audioBytes, audioBytes.length);
      socket.send(packet);

      while (!this.isInterrupted()){

        recvBytes = new byte[2000];
        packet = new DatagramPacket(recvBytes, recvBytes.length);
        socket.receive(packet);
        recvShorts = new short[packet.getLength()/2];
        ByteBuffer.wrap(packet.getData(), 0, packet.getLength()).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(recvShorts);

        player.write(recvShorts, 0, recvShorts.length);

        recordedShorts = new short[1000];
        shortsRead = recorder.read(recordedShorts, 0, recordedShorts.length);

        filteredShorts = speexEchoCancel(recordedShorts, recvShorts);

        audioBytes = new byte[shortsRead*2];
        ByteBuffer.wrap(audioBytes).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(filteredShorts);

        packet = new DatagramPacket(audioBytes, audioBytes.length);
        socket.send(packet);                

      }

and the C code with JNI is

void ava_com_example_sendaudio2_MainActivity_initEchoState_initEchoState(JNIEnv *env, jobject jobj, jint frameSize, jint filterLength){
  echo_state = speex_echo_state_init(frameSize, filterLength);
}

ava_com_example_sendaudio2_MainActivity_initEchoState_speexEchoCancel(JNIEnv *env, jobject jObj, jshortArray input_frame, jshortArray echo_frame){

  //create native shorts from java shorts
  jshort *native_input_frame = (*env)->GetShortArrayElements(env, input_frame, NULL);
  jshort *native_echo_frame = (*env)->GetShortArrayElements(env, echo_frame, NULL);

  //allocate memory for output data
  jint length = (*env)->GetArrayLength(env, input_frame);
  jshortArray temp = (*env)->NewShortArray(env, length);
  jshort *native_output_frame = (*env)->GetShortArrayElements(env, temp, 0);

  //call echo cancellation
  speex_echo_cancellation(echo_state, native_input_frame, native_echo_frame, native_output_frame);

  //convert native output to java layer output
  jshortArray output_shorts = (*env)->NewShortArray(env, length);
  (*env)->SetShortArrayRegion(env, output_shorts, 0, length, native_output_frame);

  //cleanup and return
  (*env)->ReleaseShortArrayElements(env, input_frame, native_input_frame, 0);
  (*env)->ReleaseShortArrayElements(env, echo_frame, native_echo_frame, 0);
  (*env)->ReleaseShortArrayElements(env, temp, native_output_frame, 0);
  return output_shorts;
}

this error is getting when the code use the function filteredShorts = speexEchoCancel(recordedShorts, recvShorts);

How can I resolve this ? Thanks in advance!

I am creating an app that you can use to design custom buttons easily by setting all the settings in the app and immediatly being able to see a preview. For the button, I use a shape and I have set that shape as the background. In the shape I have the normal android:width="" and android:color="" codes but I need to be able to change these in the app itself. I already have this for other aspects such as the corners using a drawable (see my question about that (solved) here.) I already tried things like drawable.setStroke() but this doesn't seem to work.

i have tried overriding the back button in android but everywhere i get errors. I want to stop the mediaplayer when i click the back button in fragment . I searched in google but there are no examples for mediaplayer only for webview there are many examples

STOREFRAGMENT.java

public class StoreFragment extends Fragment {
    View rootView;
    ImageView imageview;
    String file_url;

    final MediaPlayer mp = new MediaPlayer();
final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
private int keyCode;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    rootView = inflater.inflate(R.layout.store_home, container, false);
    return rootView;
}

@Override

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                String url = "http://localhost/Android_App/storehome.php";

                try {
                    JSONArray data = new JSONArray(getJSONUrl(url));

                    HashMap<String, String> map;

                    for (int i = 0; i < data.length(); i++) {
                        JSONObject c = data.getJSONObject(i);

                        map = new HashMap<String, String>();
                        map.put("name", c.getString("name"));

                        map.put("price", c.getString("price"));
                        map.put("image", c.getString("image"));

                        MyArrList.add(map);
                    }

                } catch (JSONException e) {

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

                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                final GridView gridView1 = (GridView) rootView.findViewById(R.id.store_home_gridview);
                gridView1.setAdapter(new ImageAdapter(getActivity(), MyArrList));
            }

        }.execute();

   }      

public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
      ImageView bmImage;

      public DownloadImageTask(ImageView bmImage) {
          this.bmImage = bmImage;
      }

      @Override
    protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap mIcon11 = null;
          try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
          } catch (Exception e) {
              bmImage.setImageResource(android.R.drawable.ic_menu_report_image);
          }
          return mIcon11;
      }

      @Override
    protected void onPostExecute(Bitmap res) {
            bmImage.setImageBitmap(res);
      }
    }


class ImageAdapter extends BaseAdapter 

{
    private Context context;
    public ImageView imageView;
    private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();

    public ImageAdapter(Context c,ArrayList<HashMap<String, String>> list) 
    {   
        context = c;

        MyArr = list;
    }

    @Override
    public int getCount() {

        return MyArr.size();
    }

    @Override
    public Object getItem(int position) {

        return position;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.store_home_gridview_row, null); 
        }






        Button play_grid = (Button)convertView.findViewById(R.id.play_gridview);
        play_grid.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                try {
                    mp.reset();
                    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
                    mp.setDataSource(tv_hidden.getText().toString());

                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) { 
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mp.prepare();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {   
                    e.printStackTrace();
                }
                mp.start();

            }

        });

        Button stop_grid = (Button)convertView.findViewById(R.id.stop_gridview);
        stop_grid.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(mp.isPlaying())
                {
                    mp.stop();
                    mp.reset();
                }   
            }

        });

        return convertView;
    }
    }



 /*** Get JSON Code from URL ***/
    public String getJSONUrl(String url) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try 
        {
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();

            if (statusCode == 200) 
            { 
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) 
                {
                    str.append(line);
                }
            }   
            else 
            {
                Log.e("Log", "Failed to download file..");
            }
        } 
        catch (ClientProtocolException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

        return str.toString();
    }
}

I added this code and i am getting an error

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            mp.stop(); //stop media player
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

If i take out the override then errors would disappear but the back button doesn't work can anyone please tell me how to add the method inside fragments

Here I need to combine these two roots....is it possible??? If yes then how????

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"`
    android:layout_width="match_parent"`
    android:layout_height="match_parent"`
    android:layout_gravity="center_vertical"`
    android:gravity="center_vertical"`
    android:orientation="vertical">`
</LinearLayout>`

<android.support.v4.widget.DrawerLayout`
    xmlns:android="http://schemas.android.com/apk/res/android"`
    android:id="@+id/drawer_layout"`
    android:layout_width="match_parent"`
    android:background="#ffffff"`
    android:layout_height="match_parent">`

    <ListView
        android:id="@android:id/list"`
        android:layout_width="240dp"`
        android:layout_height="match_parent"`
        android:layout_gravity="left"`
        android:choiceMode="singleChoice"`
        android:dividerHeight="1dp"`
        android:clickable="true"`
        android:background="@android:color/black"/>`

</`android.support.v4.widget.DrawerLayout`>`

I made an Application which made a connection to an FTP Server, using username and password. Now i'm asking my self if it's possible to encrypt my Source code, so that it's not possible to read it after making an .apk? otherwise "hackers" would be able to get my password and username.

Staromir

I have a button to show DatePicker. When I clicks the Button, it will show the DatePickerDialog. Here I'am trying to get date value and i want to fetch it in a TextView. But I'am facing difficulty when i try to fetch the value. How can i can print the date value in TextView?

Here is my code.

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1=(EditText) findViewById(R.id.editText1);
text2=(EditText) findViewById(R.id.editText2);
text3=(EditText) findViewById(R.id.editText3);
text4=(EditText) findViewById(R.id.editText4);
date=(Button) findViewById(R.id.datepicker);
date.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        DatePickerDialog dpd = new DatePickerDialog(MainActivity.this, mDateSetListener, myear, mmonth, mday);
        dpd.show();
    }
});
   final Calendar c = Calendar.getInstance();
   myear = c.get(Calendar.YEAR);
   mmonth = c.get(Calendar.MONTH);
   mday = c.get(Calendar.DAY_OF_MONTH);
}
private void updateDisplay() {
    // TODO Auto-generated method stub
    textdate.setText(new StringBuilder()
    .append(mmonth+1).append("-").append(mday).append("-")
    .append(myear));
}
private DatePickerDialog.OnDateSetListener mDateSetListener = new 
        DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                myear=year;
                mmonth=monthOfYear;
                mday=dayOfMonth;
                updateDisplay();
            }
        };

I have an application A and i also have application B to test application A. Is it possible to have an activity inside Test Application (i.e.,"B"). Could someone crack it?

I'm getting this error when trying to retrieve an image from a url using Asynctask. This is my asynctask:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap result = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            result = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
        if (result != null && !result.isRecycled()) {
            result.recycle();
            result = null;
        }
    }
}

If I remove the result.recycle(), the error would be OutofMemoryError. I'm retrieving multiple images from different url. How can I do this? I'm calling the asynctask by:

new DownloadImageTask(imageview[i]).execute(paths.get(i));

Many thanks, :)