I trying to build an audio recorder in the android studio. I followed this tutorial:
https://www.youtube.com/watch?v=XANjoeEeQ1Y
Which did not work for me? When I pushed the "record" button, nothing happened.
Therefrom I added action listeners with onClick() methods and such. Still didn't work. Then I added a text view to show me the status for debugging purpose.
After adding the status textView I found out that the beginRecording() method goes straight to the catch statement.
I watched another youtube video
https://www.youtube.com/watch?v=lWaypoRVfSc
which seems to do more or less the same thing regarding the MediaRecorder.
So.. My question is. What have I done wrong? How can I make it actually record when the RECORD button is pushed?
Thank you in advance.
Here comes my code:
package com.example.natalie.recorder;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPLayer;
private MediaRecorder recorder;
private String OUTPUT_FILE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Button startR = (Button) findViewById(R.id.startBtn);
Button stopR = (Button) findViewById(R.id.finishBtn);
Button playRecording = (Button) findViewById(R.id.playBtn);
Button stopPlaying = (Button) findViewById(R.id.stopBtn);
final TextView statusTV;
statusTV = (TextView) findViewById(R.id.statusTextView);
OUTPUT_FILE= Environment.getExternalStorageDirectory().getAbsolutePath()+"/audiorecorder.3gpp";
/*------START BUTTON------*/
startR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
beginRecording();
stv.setText("Recording");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
stv.setText("Error");
}
}
});
/*------STOP BUTTON------*/
stopR.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final TextView stv=statusTV;
try {
stopRecording();
stv.setText("Stopped");
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
Log.d("here","dd",e);
}
}
});
playRecording.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try {
playRecording();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
}
}
});
stopPlaying.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
try {
stopPlayback();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsString = sw.toString();
statusTV.setText("Error");
}
}
});
}
private void stopPlayback() throws Exception{
if(mediaPLayer != null)
mediaPLayer.stop();
}
private void playRecording() throws IOException {
ditchMediaPLayer();
mediaPLayer = new MediaPlayer();
mediaPLayer.setDataSource(OUTPUT_FILE);
mediaPLayer.prepare();
mediaPLayer.start();
}
private void ditchMediaPLayer() {
if (mediaPLayer != null) {
try{
mediaPLayer.release();
} catch(Exception e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
if(recorder != null)
recorder.stop();
}
private void beginRecording() throws Exception{
ditchMediaRecorder();
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
record.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(OUTPUT_FILE);
recorder.prepare();
recorder.start();
}
private void ditchMediaRecorder() {
if(recorder != null)
recorder.release();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The AndroidManifest look like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.natalie.recorder">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.RECORD_AUDIO"
/>
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The content_main.xml comes here:
<Button
android:id="#+id/stopBtn"
android:layout_width="249dp"
android:layout_height="56dp"
android:background="#color/colorAccent"
android:text="Stop PLayback"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/playBtn" />
<Button
android:id="#+id/playBtn"
android:layout_width="249dp"
android:layout_height="48dp"
android:background="#color/colorAccent"
android:text="Play Recording"
app:layout_constraintBottom_toTopOf="#+id/stopBtn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/finishBtn" />
<Button
android:id="#+id/finishBtn"
android:layout_width="249dp"
android:layout_height="48dp"
android:background="#color/colorAccent"
android:text="Finish Recording"
app:layout_constraintBottom_toTopOf="#+id/playBtn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/startBtn" />
<Button
android:id="#+id/startBtn"
android:layout_width="247dp"
android:layout_height="48dp"
android:background="#color/colorAccent"
android:text="Start Recording"
app:layout_constraintBottom_toTopOf="#+id/finishBtn"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/statusTextView"
android:layout_width="246dp"
android:layout_height="22dp"
android:text="Status"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintBottom_toTopOf="#+id/startBtn"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
You asked for CAMERA, WRITE_STORAGE and RECORD_AUDIO permission but you don't asked for at your activity. take a look at this.
use:
ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) to check the status of the permission and compare it with PackageManager.PERMISSION_GRANTED which mean that your permission is accepted like this :
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
}
and inside the onRequestPermissionsResult do something like this :
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//do work
}
}
Related
Image is showing nothing not even the image I chose as default no error nothing just the image cannot be loaded I granted internet permission still this is happening plz help
No error is there in logcat.
App launches everything is fine but the image wont load i tried waiting still and the API is working fine......i dunno if its my code or the permission which is causing this...
Java Code
package com.example.meme_share;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
ImageView i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView i = findViewById(R.id.imageView);
}
public void loadmeme() {
RequestQueue a = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest b = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String u = null;
try {
u = response.getString("url");
System.out.println("Raunak"+u);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Raunak"+u);
Glide.with(MainActivity.this).load(u).into(i);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
});
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button2"
android:layout_width="182dp"
android:layout_height="71dp"
android:layout_marginTop="134dp"
android:text="Next"
app:backgroundTint="#android:color/tertiary_text_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.93"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="1.0" />
<ImageView
android:id="#+id/imageView"
android:layout_width="415dp"
android:layout_height="538dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06"
tools:srcCompat="#drawable/ic_launcher_background" />
<Button
android:id="#+id/button"
android:layout_width="182dp"
android:layout_height="71dp"
android:layout_marginTop="134dp"
android:text="Share"
app:backgroundTint="#android:color/tertiary_text_light"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView"
app:layout_constraintVertical_bias="0.956" />
</androidx.constraintlayout.widget.ConstraintLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.meme_share">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Meme_Share">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
You have created two ImageView i; variables: first in onCreate methon and second in class scope.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = findViewById(R.id.imageView); // < here
}
Besides this problem here are some others:
You don't call loadmeme method anywhere
You don't make network request
ImageView imageView; // 1. Use class scoped imageView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
// 2. Run loadmeme method
loadmeme();
}
public void loadmeme() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = "https://meme-api.herokuapp.com/gimme";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String u = null;
try {
u = response.getString("url");
System.out.println("Raunak" + u);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Raunak" + u);
Glide.with(MainActivity.this).load(u).into(imageView);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error occurred", Toast.LENGTH_SHORT).show();
}
});
// 3. Add request to queue
requestQueue.add(jsonObjectRequest);
}
so I've decided to make an android application for my website (not many people read it, however I think it'll look good on my Ucas!
My problem is that after the splash screen is displayed on my phone the app crashes, I'm quite new to android app development so I'm unsure about what I'm doing wrong.
I've uploaded my sourcecode on to Github so that you can have a better look at it!
Heres some of my code:
MainActivity.java
package com.alffiw.alffisblog;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private WebView mWebView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.coderefer.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(view.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{ //if back key is pressed
if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
SplashScreen.java
package com.alffiw.alffisblog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ProgressBar
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:id="#+id/progressBar1"/>
<TextView
android:layout_below="#+id/progressBar1"
android:layout_height="wrap_content"
android:id="#+id/LoadingText"
android:layout_width="fill_parent"
android:text="Loading, Please Wait.."
android:textSize="20sp"
android:gravity="center_horizontal">
</TextView>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.alffiw.alffisblog.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/splash_image"
android:orientation="vertical">
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alffiw.alffisblog">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
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=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.coderefer.androidsplashscreenexample.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Thank you for any help in advance!
Instead of calling from thread use Handler
protected void onCreate(Bundle savedInstanceState) {
//your stuff.....
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {//just to make sure user didn,t press back button
Intent mainIntent = new Intent(Splashscreen.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
}
}, 3000);//waiting time
}
You can't call startActivity(intent) form inside the thread you've created. Firstly because startActivity(...) is a Context method and secondly, you need to execute this statement on the UI thread.
Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final Context activity = this;
Thread timerThread = new Thread(new Runnable(
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
activity.runOnUiThread(new Runnable() {
public void run(){
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
activity.startActivity(intent);
}
});
}
}
));
timerThread.start();
I have below code and have below Error when run App PLZ Help me
Main Activity
package com.comp.easybuy.easybuy;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import static android.net.Uri.parse;
public class MainActivity extends Activity {
private ImageButton callusphone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
callusphone=(ImageButton)findViewById(R.id.callus);
callusphone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, parse("tel:+962796880853"));
startActivity(callIntent);
}
});
}
public void flick(View view){
Intent bowsprit =new Intent(Intent.ACTION_VIEW, parse("http://www.facebook.com/ebuy2015/"));
startActivity(bowsprit);
}
public void incline(View view){
Intent browbeaten =new Intent(Intent.ACTION_VIEW, parse("http://www.instagram.com/easy_buy_1/"));
startActivity(browbeaten);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.offer4,
R.drawable.offer5,
R.drawable.offer6,
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding =context.getResources().
getDimensionPixelSize(R.dimen.abc_switch_padding);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Splash screen
package com.comp.easybuy.easybuy;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class Splash extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}
catch(InterruptedException e){
e.printStackTrace();
}
finally{
Intent intent = new Intent(Splash.this,MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.comp.easybuy.easybuy">
<uses-permission android:name="ANDROID.PERMISSION.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Splash"
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=".MainActivity"
android:label="#string/app_name"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
main Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:onClick="flick"
android:src="#drawable/fbook"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="false"
android:scaleType="center"
android:contentDescription="facebook Image Button"
android:layout_alignParentStart="false"
android:theme="#style/Widget.AppCompat.RatingBar"
android:visibility="visible" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/insta"
android:onClick="incline"
android:src="#drawable/inst"
android:layout_alignParentBottom="true"
android:layout_alignTop="#+id/imageButton"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:scaleType="center"
android:theme="#style/Widget.AppCompat.RatingBar"
android:visibility="visible" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/callus"
android:onClick="callusphone"
android:src="#drawable/callus"
android:layout_alignParentBottom="false"
android:layout_centerHorizontal="true"
android:layout_marginLeft="145dp"
android:layout_marginRight="145dp"
android:layout_below="#+id/view_pager"
android:layout_alignParentEnd="false"
android:layout_alignParentStart="false"
android:scaleType="center"
android:theme="#style/Widget.AppCompat.RatingBar"
android:visibility="visible" />
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignWithParentIfMissing="false"
android:layout_gravity="right|left"
android:visibility="visible"
android:background="#ffffff"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_above="#+id/imageButton" />
</RelativeLayout>
and have Error
08-19 09:30:36.123 14099-14099/com.comp.easybuy.easybuy E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.comp.easybuy.easybuy, PID: 14099
java.lang.IllegalArgumentException: Expected receiver of type com.comp.easybuy.easybuy.MainActivity, but got android.view.ContextThemeWrapper
at java.lang.reflect.Method.invoke(Native Method)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4448)
at android.view.View.performClick(View.java:5199)
at android.view.View$PerformClick.run(View.java:21155)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5415)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:725)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:615)
First declare Your Image Buttons as below
imageFb=(ImageButton)findViewById(R.id.imageButton);
imageInsta=(ImageButton)findViewById(R.id.insta);
and use OnClickListener
imageFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flick(v);
}
});
imageInsta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incline(v);
}
});
check now it should work!! You have defined your onClick in xml but havent used it and passed the view to method so it was crashing your code!
final MainActivity should look like this!
package com.comp.easybuy.easybuy;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import static android.net.Uri.parse;
public class MainActivity extends Activity {
private ImageButton callusphone;
private ImageButton imageFb;
private ImageButton imageInsta;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
callusphone=(ImageButton)findViewById(R.id.callus);
imageFb=(ImageButton)findViewById(R.id.imageButton);
imageInsta=(ImageButton)findViewById(R.id.insta);
callusphone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL, parse("tel:+962796880853"));
startActivity(callIntent);
}
});
imageFb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flick(v);
}
});
imageInsta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
incline(v);
}
});
}
public void flick(View view){
Intent bowsprit =new Intent(Intent.ACTION_VIEW, parse("http://www.facebook.com/ebuy2015/"));
startActivity(bowsprit);
}
public void incline(View view){
Intent browbeaten =new Intent(Intent.ACTION_VIEW, parse("http://www.instagram.com/easy_buy_1/"));
startActivity(browbeaten);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.offer4,
R.drawable.offer5,
R.drawable.offer6,
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding =context.getResources().
getDimensionPixelSize(R.dimen.abc_switch_padding);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(mImages[position]);
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I want to write data into a SD card but I am getting the following error: Failed open failed: EACCES (Permission denied).
The Android version I am working on is jelly bean(4.3).
I have also given permission in manifest file.
Here is my code:
package com.example.androidsdcard;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
// GUI controls
EditText txtData;
Button btnWriteSDFile;
Button btnReadSDFile;
Button btnClearScreen;
Button btnClose;
File sample=null;
String SDCard_Path="/mnt/extsd";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bind GUI elements with local controls
txtData = (EditText) findViewById(R.id.txtData);
txtData.setHint("Enter some lines of data here...");
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
File storageDir = new File(SDCard_Path);
String sample1 = Environment.getExternalStorageDirectory().getPath();
Toast.makeText(MainActivity.this,sample1, Toast.LENGTH_LONG).show();
if(sample == null)
{
Toast.makeText(MainActivity.this,"Sample == null executed", Toast.LENGTH_LONG).show();
}
else
Toast.makeText(MainActivity.this,"Sample == null skipped", Toast.LENGTH_LONG).show();
if(storageDir.isDirectory())
{
String[] dirList = storageDir.list();
if(dirList==null)
{
Toast.makeText(getBaseContext(),"Failed to detect SD card",Toast.LENGTH_SHORT).show();
return;
}
else
Toast.makeText(getBaseContext(),"SD Card Detected",Toast.LENGTH_SHORT).show();
}
try {
File myFile = new File("/mnt/extsd/MedeQuip.txt");
/* if(myFile.createNewFile()==false)
{
Toast.makeText(getBaseContext(),"Unable to create File'",Toast.LENGTH_SHORT).show();
return;
}
else
Toast.makeText(getBaseContext(),"File Created'",Toast.LENGTH_SHORT).show();
*/ FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing SD mysdfile.txt'",Toast.LENGTH_SHORT).show();
} catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnWriteSDFile
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
// write on SD card file data in the text box
try
{
File myFile = new File(SDCard_Path+"/MedeQuip.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),"Done reading SD 'MedeQuip.txt'",Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
}// onClick
}); // btnReadSDFile
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
}); // btnClearScreen
btnClose = (Button) findViewById(R.id.btnClose);
btnClose.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
finish();
}
}); // btnClose
}// onCreate
}// AndSDcard
Here is my xml:
<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">
<EditText
android:id="#+id/txtData"
android:layout_width="fill_parent"
android:layout_height="180px"
android:textSize="18sp" />
<Button
android:id="#+id/btnWriteSDFile"
android:layout_width="143px"
android:layout_height="44px"
android:layout_alignParentLeft="true"
android:layout_below="#+id/txtData"
android:layout_marginTop="60dp"
android:text="1. Write SD File" />
<Button
android:id="#+id/btnClearScreen"
android:layout_width="141px"
android:layout_height="42px"
android:layout_alignBaseline="#+id/btnWriteSDFile"
android:layout_alignBottom="#+id/btnWriteSDFile"
android:layout_marginLeft="30dp"
android:layout_toRightOf="#+id/btnWriteSDFile"
android:text="2. Clear Screen" />
<Button
android:id="#+id/btnReadSDFile"
android:layout_width="140px"
android:layout_height="42px"
android:layout_alignTop="#+id/btnWriteSDFile"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#+id/btnClearScreen"
android:text="3. Read SD File" />
<Button
android:id="#+id/btnClose"
android:layout_width="141px"
android:layout_height="43px"
android:layout_alignTop="#+id/btnClearScreen"
android:layout_marginLeft="61dp"
android:layout_toRightOf="#+id/btnReadSDFile"
android:text="4. Close" />
</RelativeLayout>
Here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidsdcard"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
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>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
You cannot assume external storage will always be at "/mnt/extsd". Very rarely will this be the case as it is up to the OEM where the mount points are. Use the standard APIs from the Context object to get the correct locations of interest: Context.getExternalFilesDir() and Context.getExternalFilesDirs().
the problem is with jelly bean
this work for me
String path = null;
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT){
path = getActivity().getCacheDir() + File.separator + "name";
} else{
path = Environment.getExternalStorageDirectory() + File.separator + "name";
}
-I have created an android app that has 2 buttons to download apks from internet server if not already installed on the device.
-I want to provide shortcut icons of these newly installed apps in my application.
I've seen a posts about launcher apps but they list out shortcuts for all apps. I want specifically for my 2 apps.
Is there a way to do it?
here's the code for existing app.
//MainActivity.java
package com.example.appcommunication;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Button app1, app2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
app1 = (Button) findViewById(R.id.button1);
app2 = (Button) findViewById(R.id.button2);
final boolean app1Installed = appInstalledOrNot("com.example.cameraphonegap");
final boolean app2Installed = appInstalledOrNot("com.example.webviewexample");
if(app1Installed){
app1.setEnabled(false);
app1.setText("App1 Installed ");
}else{
app1.setEnabled(true);
}
if(app2Installed){
app2.setEnabled(false);
app2.setText("App2 Installed ");
}else{
app2.setEnabled(true);
}
app1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("App is not installed on your phone");
Log.d("NOT installed","App not installed on your phone");
Toast.makeText(getApplicationContext(), "App1 Not Installed ", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.dropbox.com/s/9vyvypj9qxjanb/CameraPhoneGap.apk"));
startActivity(browserIntent);
}
});
app2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
System.out.println("App is not installed on your phone");
Log.d("NOT installed","App not installed on your phone");
Toast.makeText(getApplicationContext(), "App2 Not Installed ", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("https://www.dropbox.com/s/r2z299661ibmhm/webviewExample.apk"));
startActivity(browserIntent);
}
});
}
private boolean appInstalledOrNot(String uri) {
PackageManager pm = getPackageManager();
boolean app_installed = false;
try {
pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
app_installed = true;
} catch (PackageManager.NameNotFoundException e) {
app_installed = false;
}
return app_installed;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//activity_main.xml
<LinearLayout 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"
android:orientation="horizontal"
tools:context=".MainActivity"
android:background="#7FFFD4">
<Button
android:id="#+id/button1"
android:layout_marginLeft="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Install app1"
android:textStyle="bold"
/>
<Button
android:id="#+id/button2"
android:layout_marginLeft="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Install app2"
android:textStyle="bold"
/>
</LinearLayout>
//Android Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.appcommunication"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.appcommunication.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>
I implemented a workaround by saving the ic_launcher of these apps and using it as ImageButtons for launching the apps. But I need something automatic for the icons when I use the packageName of the apps..
//code for ImageButton:
ImageButton launchApp1=(ImageButton) findViewById(R.id.button3);
launchApp1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(app1Installed){
Intent LaunchIntent = getPackageManager()
.getLaunchIntentForPackage("com.example.cameraphonegap");
startActivity(LaunchIntent);}else{
Log.d("installed","App1 not installed on your phone");
Toast.makeText(getApplicationContext(),
"App1 Not Installed ", Toast.LENGTH_SHORT).show(); }
}
});
// activity_main.xml
<ImageButton
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/button1"
android:layout_marginTop="100dp"
android:layout_marginLeft="20dp"
android:background="#null"
android:contentDescription="#null"
android:src="#drawable/app1" />
How about serving these images from the server as well? You can host the images(key values for the package name?) for these apps somewhere and list them inside a listview on your app?
This is the exact thing you want to implement but using a different method to achieve it then what you are trying to do.