API doesnt work and progressBar keeps spinning - java

I am a beginner and i am trying to learn how to use APIs on android. I am doing a bitcoin price app to learn APIs. But i have a few problems.I created a progressbar and a price TextView in mainactivity.xml . I set progressbar visible and textview invisible by default.My thought is very simple, i created a new AsyncTask class and after background things are done , i will set the progressbar invisible and the textview visible in the onPostExecute() to show price. But it didn't work. The progressbar keeps spinning, it doesn't show the price i dont understand why it doesn't work.
The API i am using
MainActivity
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.InputStreamReader;
import java.io.BufferedReader;
public class MainActivity extends AppCompatActivity {
public static String line;
public static ProgressBar progressBar;
static String API_URL="https://api.coindesk.com/v1/bpi/currentprice/try.json";
static TextView priceTextView;
static TextView timeTextView;
static int priceInt;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
priceTextView=(TextView)findViewById(R.id.priceText);
timeTextView=(TextView)findViewById(R.id.timeText);
progressBar=(ProgressBar)findViewById(R.id.progressBar);
retrievePriceTask retrievePriceTask=new retrievePriceTask();
retrievePriceTask.execute();
}
}
class retrievePriceTask extends AsyncTask <Void,Void,String>{
#Override
protected void onPreExecute() {
MainActivity.progressBar.setVisibility(View.VISIBLE);
MainActivity.priceTextView.setVisibility(View.INVISIBLE);
}
#Override
protected String doInBackground(Void... urls) {
try {
URL url = new URL(MainActivity.API_URL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((MainActivity.line = bufferedReader.readLine()) != null) {
stringBuilder.append(MainActivity.line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
#Override
protected void onPostExecute(String s) {
MainActivity.priceTextView.setVisibility(View.VISIBLE);
MainActivity.progressBar.setVisibility(View.INVISIBLE);
try{
JSONObject jsonObject=(JSONObject)new JSONTokener(MainActivity.line).nextValue();
MainActivity.priceInt=jsonObject.getJSONObject("bpi").getJSONObject("TRY").getInt("rate");
MainActivity.priceTextView.setText(MainActivity.priceInt);
}
catch (Exception e){
e.printStackTrace();
}
}
}
My Logcat
07-16 10:20:08.884 2269-2269/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 2269
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setVisibility(int)' on a null object reference
at zaaa.trinki.retrievePriceTask.onPreExecute(MainActivity.java:94)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:55)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
07-16 10:37:42.062 16262-16262/zaaa.trinki E/AndroidRuntime: FATAL EXCEPTION: main
Process: zaaa.trinki, PID: 16262
java.lang.RuntimeException: Unable to start activity ComponentInfo{zaaa.trinki/zaaa.trinki.MainActivity}: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x0
at android.content.res.Resources.getText(Resources.java:274)
at android.support.v7.widget.ResourcesWrapper.getText(ResourcesWrapper.java:52)
at android.widget.TextView.setText(TextView.java:4122)
at zaaa.trinki.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5221) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 

Use a ProgressDialog instead of a ProgressBar:
ProgressDialog myProgressDialog = ProgressDialog.show(Context CONTEXT, String TITLE, String MESSAGE, boolean INDETERMINATE, boolean CANCELABLE);
myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
and in your onPostExecute() just put myProgressDialog.dismiss()

Related

ble beacon transmitter app close once it run

i am trying to create an app to transmit beacons from android 5.0 devices but i get this error
{09-07 10:23:45.184 3057-3057/com.example.mohamed_pc.test2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.mohamed_pc.test2, PID: 3057
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mohamed_pc.test2/com.example.mohamed_pc.test2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.le.BluetoothLeAdvertiser android.bluetooth.BluetoothAdapter.getBluetoothLeAdvertiser()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.le.BluetoothLeAdvertiser android.bluetooth.BluetoothAdapter.getBluetoothLeAdvertiser()' on a null object reference
at com.example.mohamed_pc.test2.MainActivity.onCreate(MainActivity.java:31)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) }
The code is below
package com.example.mohamed_pc.test2;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.nio.ByteBuffer;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
private BluetoothLeAdvertiser mBluetoothLeAdvertiser;
private AdvertiseData mAdvertiseData;
private AdvertiseSettings mAdvertiseSettings;
private AdvertiseCallback mAdvertiseCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothLeAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
}
public void buttonOnClick(View v) {
// do something when the button is clicked
Button button=(Button) v;
((Button) v).setText("clicked");
setAdvertiseData();
setAdvertiseSettings();
mBluetoothLeAdvertiser.startAdvertising(mAdvertiseSettings, mAdvertiseData, mAdvertiseCallback);
}
protected void setAdvertiseData() {
AdvertiseData.Builder mBuilder = new AdvertiseData.Builder();
ByteBuffer mManufacturerData = ByteBuffer.allocate(24);
byte[] uuid = getIdAsByte(UUID.fromString("0CF052C297CA407C84F8B62AAC4E9020"));
mManufacturerData.put(0, (byte)0xBE); // Beacon Identifier
mManufacturerData.put(1, (byte)0xAC); // Beacon Identifier
for (int i=2; i<=17; i++) {
mManufacturerData.put(i, uuid[i-2]); // adding the UUID
}
mManufacturerData.put(18, (byte)0x00); // first byte of Major
mManufacturerData.put(19, (byte)0x09); // second byte of Major
mManufacturerData.put(20, (byte)0x00); // first minor
mManufacturerData.put(21, (byte)0x06); // second minor
mManufacturerData.put(22, (byte)0xB5); // txPower
mBuilder.addManufacturerData(224, mManufacturerData.array()); // using google's company ID
mAdvertiseData = mBuilder.build();
}
protected void setAdvertiseSettings() {
AdvertiseSettings.Builder mBuilder = new AdvertiseSettings.Builder();
mBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_POWER);
mBuilder.setConnectable(false);
mBuilder.setTimeout(0);
mBuilder.setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM);
mAdvertiseSettings = mBuilder.build();
}
public static byte[] getIdAsByte(java.util.UUID uuid)
{
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
}
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
is giving you null. Check permisses and if bluetooth is enabled
Changed the format:
UUID.fromString("0CF052C297CA407C84F8B62AAC4E9020")
By:
UUID.fromString("0CF052C2-97CA-407C-84F8-B62AAC4E9020");

Onclick button method in fragment

I created simple application in android. I have a user profile in navigation drawer. when choose address option in that drawer Open that fragment (Example:Address fragment). In that layout i put save button. While click that save button i want validate all the fields. But, when i choose that option from the drawer, application unfortunately stopped.
My code here:
AddressFragment.java
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddressFragment extends Fragment {
EditText line2;
Button addrsave;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_address, container, false);
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
// Get a reference to the AutoCompleteTextView in the layout
AutoCompleteTextView textView = (AutoCompleteTextView) view.findViewById(R.id.city_autoCompleteTextView);
// Get the string array
String[] city = getResources().getStringArray(R.array.city);
// Create the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, city);
textView.setAdapter(adapter);
addrsave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String addr = line2.getText().toString();
if (addr.equals("")) {
Toast.makeText(getActivity().getApplicationContext(), "Field cannot be left blank.", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
}
My logcat:
07-22 12:47:46.235 6355-6355/com.h2o E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.h2o, PID: 6355
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.h2o/com.h2o.AccountActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.h2o.AddressFragment.onCreateView(AddressFragment.java:38)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1220)
at android.app.Activity.performStart(Activity.java:5953)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Please anyone help!!
Thanks in advance!!!
Change this:
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
to this:
addrsave = (Button) view.findViewById(R.id.addrsave);
Problem is that you are doing findViewById() on getActivity() which gives you a null. And then setting an onClickListener on it will throw NullPointerException.
Hope it helps! :)
Change this line
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
to
addrsave = (Button) view.findViewById(R.id.addrsave);
Your R.layout.fragment_layout_address is assigned to view so you have to use view variable to get the button from layout. Secondly, Also initialize line2 which will throw an exception of NPE(Null Pointer) once you resolve the first issue
I cant see where you have initialized line2 ?
So line2 is null which might cause the exception
String addr = line2.getText().toString();
I think you have added button in fragment and you are trying to retrive it from activity. So change retrieving the view from getActivity() to view like below
addrsave = (Button) getActivity().findViewById(R.id.addrsave);
Replace the above with the following line
addrsave = (Button) view.findViewById(R.id.addrsave);
And You missed the line2 view initialization in line number 38

Android MediaRecorder NullPointerException

Im just starting out with Java Development and i am fiddling around with the Android Media recorder. However I am getting a NullPointerException which I click the record button using the following source code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
//import android.net.Uri;
import android.view.Menu;
import android.view.MenuItem;
import android.os.Environment;
import android.view.View;
import java.io.File;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import java.lang.String;
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder = new MediaRecorder();
// Uri target = Uri.parse(outputFile.getAbsolutePath());
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
}
public void Start_Record(View v)
{
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myAudioRecorder.stop();
myAudioRecorder.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);
}
}
I realise that this probably due to the fill pointer being set to NULL, however I am struggling to see how to initialize the file reference for this to vanish. I am getting th exception on mediaRecorderPrepare()
Here is the Exception thrown:
03-09 22:53:56.548 31836-31836/uk.co.spectralgear.spectralboost E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaRecorder.prepare()' on a null object reference
at uk.co..MainActivity.Start_Record(MainActivity.java:38)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at android.view.View$1.onClick(View.java:4002)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Any help would be greatly appreciated:)
PROBLEM:
Your class variable "myAudioRecord" is null when "Start_Record()" tries to use it:
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method 'void Android.media.MediaRecorder.prepare()' on a null object reference
SOLUTION: Delete this line from your "onCreate()" method:
public class MainActivity extends ActionBarActivity {
String outputFile = "test.3gp";
private MediaRecorder myAudioRecorder; // Your class variable: OK...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// MediaRecorder myAudioRecorder = new MediaRecorder(); // DELETE THIS LINE!!!
myAudioRecorder = new MediaRecorder(); // OK...
...
The declaration of "myAudioRecorder" inside onCreate() HIDES the outer declaration. So the outer (class-level) "myAudioRecorder" never gets initialized ... and your program dies with an NPE when "Start_Record()" tries to access it.
PS:
Please consider changing the method name to "start_Record()". Or better, "startRecord()". This is more consistent with Java naming conventions.
I think you are using stop() function while it was already stopped. Check your code and logic.

BufferedRead runtime crash

My app crash when encounters BufferedReader operation. Ive tried to implement the code inside an asyncTask classe, because ive read that the crash is caused by the ui thread, but nothing has changed.
public class URLConnectionReader extends AsyncTask<URL, Void, String> {
String result = null;
#Override
protected String doInBackground(URL... params) {
String result = null;
URL url = (params[0]);
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
url.openStream()
)
);
}catch (IOException e){
e.printStackTrace();
}
return result;
}
}
Logs
03-02 13:28:43.215 25186-25186/com.example.jsonreader E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.jsonreader, PID: 25186
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jsonreader/com.example.jsonreader.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:373)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:323)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:190)
at java.net.URL.openStream(URL.java:470)
at com.example.jsonreader.URLConnectionReader.doInBackground(URLConnectionReader.java:38)
at com.example.jsonreader.MainActivity.onCreate(MainActivity.java:27)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
MainActivity code
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
URL address = new URL("http://www.youth-stories.com/api/all.php");
URLConnectionReader reader = new URLConnectionReader();
String result = reader.doInBackground(address);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
}catch (IOException e){
e.printStackTrace();
}
i solved the problem to get back data using the .get instruction
String result = reader.execute(address).get();

Error creating Relative Layout using Java Code

i am new to android development and was trying to create RelativeLayout using Java code.
Below is my MainActivty.java
package com.rt.droid.rellayoutjava;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;
public class MainActivity extends Activity {
RelativeLayout r;
public static LayoutParams msgDim;
EditText userNameVal, passwordVal;
TextView message, userName, password;
Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
createMessage();
r.addView(message,msgDim);
setContentView(r);
}
public void init() {
r = new RelativeLayout(this);
LayoutParams dimensions = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
r.setLayoutParams(dimensions);
userNameVal = new EditText(this);
passwordVal = new EditText(this);
message=new TextView(this);
userName = new TextView(this);
password = new TextView(this);
login = new Button(this);
}
public void createMessage(){
LayoutParams msgDim = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
msgDim.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
message.setLayoutParams(msgDim);
message.setText("Please login first");
message.setTextColor(Color.rgb(0,0,0));
}
}
However i get the null pointer exception(below from Logcat)
Process: com.rt.droid.rellayoutjava, PID: 2471
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rt.droid.rellayoutjava/com.rt.droid.rellayoutjava.MainActivity}: java.lang.NullPointerException: Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to read from field 'int android.view.ViewGroup$LayoutParams.width' on a null object reference
at android.view.ViewGroup$LayoutParams.<init>(ViewGroup.java:6403)
at android.view.ViewGroup$MarginLayoutParams.<init>(ViewGroup.java:6685)
at android.widget.RelativeLayout$LayoutParams.<init>(RelativeLayout.java:1345)
at android.widget.RelativeLayout.generateLayoutParams(RelativeLayout.java:1104)
at android.view.ViewGroup.addViewInner(ViewGroup.java:3889)
at android.view.ViewGroup.addView(ViewGroup.java:3733)
at android.view.ViewGroup.addView(ViewGroup.java:3709)
at com.rt.droid.rellayoutjava.MainActivity.onCreate(MainActivity.java:24)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Any pointers would be appreciated.
First of all, I suggest you to use XML files to define your layout, instead of writing them programmatically (you can search for any kind of example and tutorial).
Anyway, your specific problem is related to the variable msgDim which is not initialized. Change your onCreate() to this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
init();
createMessage();
msgDim = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
r.addView(message,msgDim);
setContentView(r);
}
Try using this:
r = new RelativeLayout(this);
RelativeLayout.LayoutParams dimensions = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
r.setLayoutParams(dimensions);
The first answer under this question has more complete code: Programatically creating a RelativeLayout in Android

Categories