Save Audio record to File Object - java

Im trying to save an Audio record from the Microphone, to a File Object, instead of a File. Why? Because i only need to save the record, while the App is active. This is what i tried, using the "Audio Capture" tutorial from developer.android.com
private Button b1;
private Button b2;
private ProgressBar bar;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private boolean recording = false;
private boolean playing = false;
public AudioRecordDialog(Context context, final MainActivity main) {
super(context);
setTitle(R.string.setupSound);
setContentView(R.layout.audio_record_dialog_layout);
bar = (ProgressBar) findViewById(R.id.progressBar1);
bar.setAlpha(0);
b1 = (Button) findViewById(R.id.button1);
b1.setText(R.string.startButton);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (recording) {
b1.setText(R.string.startButton);
recording = false;
bar.setAlpha(0);
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
}
mRecorder = null;
} else {
b1.setText(R.string.stopButton);
recording = true;
bar.setAlpha(1);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mRecorder.setOutputFile("record.3gp");
try {
mRecorder.prepare();
} catch (IOException e) {
Toast toast = Toast.makeText(getContext(),
"Failed Recording!", Toast.LENGTH_SHORT);
toast.show();
}
mRecorder.start();
}
}
});
b2 = (Button) findViewById(R.id.button2);
b2.setText(R.string.playButton);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (playing) {
b2.setText(R.string.playButton);
playing = false;
if (mPlayer != null)
mPlayer.release();
mPlayer = null;
} else {
b2.setText(R.string.pauseButton);
playing = true;
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource("record.3gp");
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Toast toast = Toast.makeText(getContext(),
"Failed Playing soundFile!",
Toast.LENGTH_SHORT);
toast.show();
}
}
}
});
But it doesnt work and crashes upon clicking the record-Button.
Here is the logCat.
08-28 02:07:14.144: E/Trace(17588): error opening trace file: Permission denied (13)
08-28 02:07:14.324: D/SensorManager(17588): caller of registerListener:17588,sensor type:3
08-28 02:07:14.410: D/libEGL(17588): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
08-28 02:07:14.425: D/libEGL(17588): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
08-28 02:07:14.425: D/libEGL(17588): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
08-28 02:07:14.511: D/OpenGLRenderer(17588): Enabling debug mode 0
08-28 02:07:17.785: E/MediaRecorder(17588): start called in an invalid state: 4
08-28 02:07:17.785: D/AndroidRuntime(17588): Shutting down VM
08-28 02:07:17.785: W/dalvikvm(17588): threadid=1: thread exiting with uncaught exception (group=0x40ddd2a0)
08-28 02:07:17.793: E/AndroidRuntime(17588): FATAL EXCEPTION: main
08-28 02:07:17.793: E/AndroidRuntime(17588): java.lang.IllegalStateException
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.media.MediaRecorder.start(Native Method)
08-28 02:07:17.793: E/AndroidRuntime(17588): at com.notfall.notruf.AudioRecordDialog$1.onClick(AudioRecordDialog.java:74)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.view.View.performClick(View.java:4106)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.view.View$PerformClick.run(View.java:17052)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.os.Handler.handleCallback(Handler.java:615)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.os.Handler.dispatchMessage(Handler.java:92)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.os.Looper.loop(Looper.java:137)
08-28 02:07:17.793: E/AndroidRuntime(17588): at android.app.ActivityThread.main(ActivityThread.java:5118)
08-28 02:07:17.793: E/AndroidRuntime(17588): at java.lang.reflect.Method.invokeNative(Native Method)
08-28 02:07:17.793: E/AndroidRuntime(17588): at java.lang.reflect.Method.invoke(Method.java:511)
08-28 02:07:17.793: E/AndroidRuntime(17588): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
08-28 02:07:17.793: E/AndroidRuntime(17588): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
08-28 02:07:17.793: E/AndroidRuntime(17588): at dalvik.system.NativeStart.main(Native Method)
08-28 02:07:19.191: I/Process(17588): Sending signal. PID: 17588 SIG: 9
it crashes on
mRecorder.start();

You should call setAudioEncoder() after setOutputFormat().

Related

The api isApiSupported return true but SipManager newInstance still return null in Android native Sip

I used Android native Sip api to initialize Sip client.Because I am confused to Sip protocol,I read the android developer document about sip and follow it.When I run my application on Nexus5,it work normally,but when I run it on other device like coolpad, it throw NullPointException from SipManager.The following is my code.For some reason,the username,passwd and domain is private.
public static SipManager manager;
public static SipProfile me;
public static String username;
public static String passwd;
public static void initializeSip(Context context) {
System.out.println("initializeSip");
if (manager == null) {
manager = SipManager.newInstance(context);
}
if (me != null) {
closeLocalProfile();
}
username = SharedPreferences.getLoginInfo().getModel().getVos_phone();
passwd = SharedPreferences.getLoginInfo().getModel().getVos_phone_pwd();
try {
if (!(SipManager.isApiSupported(context) && SipManager.isVoipSupported(context))) {
System.out.println("cannot support");
return;
}
System.out.println("isApiSupported="+SipManager.isApiSupported(context));
System.out.println("SipManager="+SipManager.newInstance(context));
SipProfile.Builder builder = new SipProfile.Builder(username, domain);
builder.setPassword(passwd);
me = builder.build();
manager.open(me);
SipRegistrationListener listener = new SipRegistrationListener() {
#Override
public void onRegistering(String localProfileUri) {
System.out.println("Registering with SIP Server");
}
#Override
public void onRegistrationDone(String localProfileUri, long expiryTime) {
System.out.println("Register success");
}
#Override
public void onRegistrationFailed(String localProfileUri, int errorCode, String errorMessage) {
System.out.println("Registeration failed.Please check Settings.");
System.out.println("errorCode="+errorCode);
System.out.println("errorMessage="+errorMessage);
}
};
manager.setRegistrationListener(me.getUriString(),listener);
manager.register(me,3000,listener);
} catch (ParseException e) {
e.printStackTrace();
} catch (SipException e) {
e.printStackTrace();
}
}
The following is my logcat. Most strangely,I find that the api isApiSupported return true and the SipManager object is not null.I cannot find the reason about it.
1.741 30654-30654/com.dev.goldunion I/System.out: initializeSip
05-18 20:11:41.741 30654-30654/com.dev.goldunion I/System.out: isApiSupported=true
05-18 20:11:41.751 30654-30654/com.dev.goldunion I/System.out: SipManager=android.net.sip.SipManager#426af938
05-18 20:11:41.751 30654-30654/com.dev.goldunion D/AndroidRuntime: Shutting down VM
05-18 20:11:41.751 30654-30654/com.dev.goldunion W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41692970)
05-18 20:11:41.751 30654-30654/com.dev.goldunion E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dev.goldunion/com.dev.goldunion.activity.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2227)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.access$600(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5265)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.net.sip.SipManager.open(SipManager.java:180)
at com.dev.goldunion.util.RegisterSipAccountUtils.initializeSip(RegisterSipAccountUtils.java:49)
at com.dev.goldunion.activity.MainActivity.onCreate(MainActivity.java:77)
at android.app.Activity.performCreate(Activity.java:5146)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1090)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2191)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2282) 
at android.app.ActivityThread.access$600(ActivityThread.java:147) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5265) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:525) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:760) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576) 
at dalvik.system.NativeStart.main(Native Method) 

Calling MediaRecorder crashes app in AndroidStudio

I am trying to create a class that sets and starts audio recording but as soon as I click the button the app crashes. Iv isolated the problem to where I set the parameters for the MediRecorder.
private void startRec() throws IOException {
if (mrecorder!=null)
mrecorder.release();
mrecorder= new MediaRecorder();
-> mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
/*
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrecorder.setOutputFile(MFILE);
mrecorder.prepare();
mrecorder.start();
*/
}
It crashes when the line with the arrow above the start of the notes is executed. I added the following permission to the manifest as well:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Any help much appreciated.
UPDATED LOGCAT
[ 05-12 00:39:13.299 30086:30158 D/ ]
ro.exynos.dss isEnabled: 0
05-12 00:39:13.309 30086-30158/record66.record6 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
05-12 00:39:13.319 30086-30086/record66.record6 W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
05-12 00:39:13.319 30086-30158/record66.record6 D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : record66.record6
05-12 00:39:13.359 30086-30086/record66.record6 D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
05-12 00:39:13.389 30086-30086/record66.record6 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#682466c time:234401322
05-12 00:39:15.749 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 0
05-12 00:39:15.879 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 1
05-12 00:39:15.929 30086-30086/record66.record6 D/AndroidRuntime: Shutting down VM
05-12 00:39:15.939 30086-30086/record66.record6 E/AndroidRuntime: FATAL EXCEPTION: main
Process: record66.record6, PID: 30086
java.lang.RuntimeException: setAudioSource failed.
at android.media.MediaRecorder._setAudioSource(Native Method)
at android.media.MediaRecorder.setAudioSource(MediaRecorder.java:488)
at record66.record6.MainActivity.startRec(MainActivity.java:58)
at record66.record6.MainActivity.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
05-12 00:39:17.909 30086-30086/record66.record6 I/Process: Sending signal. PID: 30086 SIG: 9
Please see what logcat is.
And let us know what error you are getting. So can help.
package com.example.dhrupalpatel.test;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity implements View.OnClickListener{
MediaRecorder mrecorder;
boolean mStartRecording=false;
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start =(Button)findViewById(R.id.start);
stop =(Button)findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
private void startRec() throws IOException {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
File sdCardDirectory= Environment
.getExternalStorageDirectory();
if(mExternalStorageAvailable && !sdCardDirectory.exists())
{
sdCardDirectory.mkdir();
}
File f= new File(sdCardDirectory.getPath()+"/"+System.currentTimeMillis()+".mp3");
if( mrecorder == null ) {
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setOutputFile(f.getPath());
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if(!mStartRecording) {
try {
mrecorder.prepare();
mrecorder.start();
mStartRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRec() throws IOException {
if(mStartRecording) {
mStartRecording = false;
mrecorder.stop();
mrecorder.reset();
mrecorder.release();
mrecorder = null;
}
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.start:
try {
startRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stop:
try {
stopRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}

How do I solve IabHelper Error

I have an error on 264 and 163 of two file but in editor it's look fine
line 264 :
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
line 163 :
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
I can't find why my activity unable to start
Logcat:
1266-1266/com.exercise.AndroidHTML E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exercise.AndroidHTML/com.company.clipboard.AndroidHTMLActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.company.clipboard.util.IabHelper.startSetup(IabHelper.java:264)
at com.company.clipboard.AndroidHTMLActivity.onCreate(AndroidHTMLActivity.java:163)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at android.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at android.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This is the whole block of payment that contain line 163:
//=====================================================
String base64EncodedPublicKey = "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDtUWVdLt6clZldCQGZxcyyWeeBp8vF/6qm7qCKuQPdXg6HB71hVu8lmcEO0VcyS2xpzXt03iW7LhKXRtDsxi5H9wHLESfY9SQUc0ugPD+n5nE+I6zCiB/RB2WscvZFa3JCiYRbmsvez+DwaQSHfq6CNUawl0fbz4NfJntZHKYHanm6PtjquO9JSj+Pa9PV38C3o5Y3ALCvPMCAwEAAQ==";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
Log.d(TAG, "Query inventory finished.");
if (result.isFailure()) {
Log.d(TAG, "Failed to query inventory: " + result);
return;
}
else {
Log.d(TAG, "Query inventory was successful.");
// does the user have the premium upgrade?
mIsPremium = inventory.hasPurchase(SKU_PREMIUM);
if (mIsPremium){
MasrafSeke(inventory.getPurchase(SKU_PREMIUM));
}
// update UI accordingly
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
if (result.isFailure()) {
Log.d(TAG, "Error purchasing: " + result);
return;
}
else if (purchase.getSku().equals(SKU_PREMIUM)) {
// give user access to premium content and update the UI
Toast.makeText(AndroidHTMLActivity.this,"خرید موفق",Toast.LENGTH_SHORT).show();
MasrafSeke(purchase);
}
}
};
Log.d(TAG, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Seems an issue of IabHelper. The method queryIntentServices returns a null, instead an empty list.
Try to update the code from this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}
to this:
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
List<ResolveInfo> intentServices = mContext.getPackageManager().queryIntentServices(serviceIntent, 0);
if (intentServices != null && intentServices.isEmpty() == false) {
// service available to handle that Intent
mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
else {
// no service available to handle that Intent
if (listener != null) {
listener.onIabSetupFinished(
new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE,
"Billing service unavailable on device."));
}
}

NetWork On main thread Exception

Hi, I try to check network connectivity and Internet present by using following method
check = new ConnectionDetector(getApplicationContext());
conn = check.isConnectingToInternet();
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
/*public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}*/
public boolean isConnectingToInternet(){
try{
ConnectivityManager cm = (ConnectivityManager)_context.getSystemService
(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
Log.d("NetInfo", String.valueOf(netInfo));
if (netInfo != null && netInfo.isConnected())
{
//Network is available but check if we can get access from the network.
URL url = new URL("http://www.Google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(2000); // Timeout 2 seconds.
urlc.connect();
Log.d("NetInfo Response Code", String.valueOf(urlc.getResponseCode()));
// Toast.makeText(getApplicationContext(), String.valueOf(urlc.getResponseCode()), Toast.LENGTH_LONG).show();
if (urlc.getResponseCode() == 200) //Successful response.
{
return true;
}
else
{
Log.d("NO INTERNET", "NO INTERNET");
return false;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
}
Note :
But this will return NetworkOnMainThread Exception like follows.kindly any one suggest me what mistakes i made.......
03-27 12:53:35.617: W/System.err(1095): android.os.NetworkOnMainThreadException
03-27 12:53:35.627: W/System.err(1095): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
03-27 12:53:35.637: W/System.err(1095): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
03-27 12:53:35.637: W/System.err(1095): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
03-27 12:53:35.647: W/System.err(1095): at java.net.InetAddress.getAllByName(InetAddress.java:220)
03-27 12:53:35.647: W/System.err(1095): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
03-27 12:53:35.657: W/System.err(1095): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
03-27 12:53:35.668: W/System.err(1095): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
03-27 12:53:35.668: W/System.err(1095): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
03-27 12:53:35.677: W/System.err(1095): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
03-27 12:53:35.687: W/System.err(1095): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-27 12:53:35.699: W/System.err(1095): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
03-27 12:53:35.699: W/System.err(1095): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-27 12:53:35.707: W/System.err(1095): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-27 12:53:35.718: W/System.err(1095): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
03-27 12:53:35.727: W/System.err(1095): at com.slet.routemytrips.beta.ConnectionDetector.isConnectingToInternet(ConnectionDetector.java:50)
03-27 12:53:35.727: W/System.err(1095): at com.slet.routemytrips.beta.Disclaimer$1.onClick(Disclaimer.java:178)
03-27 12:53:35.738: W/System.err(1095): at android.view.View.performClick(View.java:3480)
03-27 12:53:35.738: W/System.err(1095): at android.view.View$PerformClick.run(View.java:13983)
03-27 12:53:35.748: W/System.err(1095): at android.os.Handler.handleCallback(Handler.java:605)
03-27 12:53:35.757: W/System.err(1095): at android.os.Handler.dispatchMessage(Handler.java:92)
03-27 12:53:35.757: W/System.err(1095): at android.os.Looper.loop(Looper.java:137)
03-27 12:53:35.767: W/System.err(1095): at android.app.ActivityThread.main(ActivityThread.java:4340)
03-27 12:53:35.777: W/System.err(1095): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 12:53:35.777: W/System.err(1095): at java.lang.reflect.Method.invoke(Method.java:511)
03-27 12:53:35.787: W/System.err(1095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
03-27 12:53:35.797: W/System.err(1095): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
03-27 12:53:35.807: W/System.err(1095): at dalvik.system.NativeStart.main(Native Method)
03-27 12:57:05.237: D/dalvikvm(90): GC_CONCURRENT freed 666K, 10% free 12624K/14023K, paused 6ms+10ms
You can't make HTTP requests on the main thread, it would cause the UI to freeze up. So it throws that exception. You need to do it in an AsyncTask or another Thread.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
NetworkOnMainThreadException is thrown if you attempt to make a network request in the main UI Thread. So all network related operation should be done on the background thread.
AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.
http://developer.android.com/reference/android/os/AsyncTask.html
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)
{
//http request. do not update ui here
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui
}
}
An alternative to asynctask is Robospice. Can make multiple spice request. Notifies on the ui thread. https://github.com/octo-online/robospice
To check Netowrk Connectivity.
In your activity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(CheckNetwork.isInternetAvailable(MainActivity.this))
{
//call asyntask and make http request.
}
}
CheckNetwork class
public class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
return true;
}
}
}
}

Twitter: After giving username and password the app gets crash

In my android application the data has to be shared using twitter so had followed this link http://androidcodeexamples.blogspot.in/2011/12/how-to-integrate-twitter-in-android.html, everything works fine, but after giving username and password, getting force close option.
here's the logcat output
01-17 17:07:54.118: E/AndroidRuntime(383): FATAL EXCEPTION: main
01-17 17:07:54.118: E/AndroidRuntime(383): java.lang.NullPointerException
01-17 17:07:54.118: E/AndroidRuntime(383): com.twitter.android.TwitterApp$1.handleMessage(TwitterApp.java:237)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.os.Looper.loop(Looper.java:123)
01-17 17:07:54.118: E/AndroidRuntime(383): at android.app.ActivityThread.main(ActivityThread.java:3683)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 17:07:54.118: E/AndroidRuntime(383): at java.lang.reflect.Method.invoke(Method.java:507)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-17 17:07:54.118: E/AndroidRuntime(383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-17 17:07:54.118: E/AndroidRuntime(383): at dalvik.system.NativeStart.main(Native Method)
this is the code in mainactivity
public class Singlemenuitem extends Activity {
private TwitterApp mTwitter;
private static final String CONSUMER_KEY = "6JyIkj71ZqG4wk3YF0Y4hw";
private static final String CONSUMER_SECRET = "sJl9aRVqlEt7nxlKvpMVK6tLULz5FSQ2KUOW0yie4";
private enum FROM {
TWITTER_POST, TWITTER_LOGIN
};
private enum MESSAGE {
SUCCESS, DUPLICATE, FAILED, CANCELLED
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
mTwitter = new TwitterApp(this, CONSUMER_KEY, CONSUMER_SECRET);
//share twitter
final ImageView twitter = (ImageView) findViewById(R.id.twitter);
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
mTwitter.resetAccessToken();
if (mTwitter.hasAccessToken() == true) {
try {
mTwitter.updateStatus(String.valueOf(Html
.fromHtml(TwitterApp.MESSAGE)));
// File f = new File("/mnt/sdcard/android.jpg");
// mTwitter.uploadPic(f, String.valueOf(Html
// .fromHtml(TwitterApp.MESSAGE)));
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
} else {
mTwitter.authorize();
}
}
private void postAsToast(FROM twitterPost, MESSAGE success) {
switch (twitterPost) {
case TWITTER_LOGIN:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Login Successful", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Login Failed", Toast.LENGTH_LONG).show();
default:
break;
}
break;
case TWITTER_POST:
switch (success) {
case SUCCESS:
Toast.makeText(Singlemenuitem.this, "Posted Successfully", Toast.LENGTH_LONG)
.show();
break;
case FAILED:
Toast.makeText(Singlemenuitem.this, "Posting Failed", Toast.LENGTH_LONG)
.show();
break;
case DUPLICATE:
Toast.makeText(Singlemenuitem.this,
"Posting Failed because of duplicate message...",
Toast.LENGTH_LONG).show();
default:
break;
}
break;
}
TwDialogListener mTwLoginDialogListener = new TwDialogListener() {
public void onError(String value) {
postAsToast(FROM.TWITTER_LOGIN, MESSAGE.FAILED);
Log.e("TWITTER", value);
mTwitter.resetAccessToken();
}
public void onComplete(String value) {
try {
mTwitter.updateStatus(TwitterApp.MESSAGE);
postAsToast(FROM.TWITTER_POST, MESSAGE.SUCCESS);
} catch (Exception e) {
if (e.getMessage().toString().contains("duplicate")) {
postAsToast(FROM.TWITTER_POST, MESSAGE.DUPLICATE);
}
e.printStackTrace();
}
mTwitter.resetAccessToken();
}

Categories