I am using okhttp for network requests and responses.I have searched alot on the web and also on github about this issue but i did not get any clean solution, I don't know what is wrong in the code. I am getting NullPointerException when i click on Btn_Proceed. The code is provided and also the stacktrace. Thank you.
07-28 02:11:18.407 16167-17029/com.donateblood.blooddonation E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.donateblood.blooddonation, PID: 16167
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.NullPointerException
at okhttp3.HttpUrl.canonicalize(HttpUrl.java:1853)
at okhttp3.FormBody$Builder.add(FormBody.java:110)
at com.donateblood.blooddonation.UploadImage$AddUserAsync.doInBackground(UploadImage.java:203)
at com.donateblood.blooddonation.UploadImage$AddUserAsync.doInBackground(UploadImage.java:173)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:864)
public class UploadImage extends AppCompatActivity {
#InjectView(R.id.imageView) ImageView ImageUpload;
#InjectView(R.id.upload) Button Btn_Upload;
#InjectView(R.id.proceed) Button Btn_Proceed;
EditText code;
public ProgressDialog pDialog;
public String bloodgroup,name,password,number,email,age,ID;
public String encodedPhotoString=null;
GPSTracker gps; public Bitmap myimage=null;
public JSONObject json =null;
public double latitude;
public double longitude;
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try{
setContentView(R.layout.uploadimage);
ButterKnife.inject(this);
}catch (OutOfMemoryError e){
Toast.makeText(getBaseContext(), "Sorry,Something went wrong", Toast.LENGTH_SHORT).show();
}
code = (EditText) findViewById(R.id.code);
myimage = CroppingActivity.finalImage;
CheckImage();
// Upload image ====================================
Btn_Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), CroppingActivity.class);
startActivity(intent);
UploadImage.this.finish();
}
});
Btn_Proceed.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(code.length()==0){
Toast.makeText(getBaseContext(), "Enter verification code", Toast.LENGTH_LONG).show();
}
else {
Prcoess();
}
}
});
}
public void CheckImage(){
if(myimage!=null){
Uri uri = getImageUri(myimage);
String url = getRealPathFromURI(uri);
File file = new File(url);
Glide.with(UploadImage.this).load(file).asBitmap().diskCacheStrategy( DiskCacheStrategy.NONE ).skipMemoryCache( true ).override(300,300)
.transform(new CenterCrop(UploadImage.this),new CustomCenterCrop(UploadImage.this)).into(ImageUpload);
}else {
encodedPhotoString= null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = UploadImage.this.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public Uri getImageUri( Bitmap inImage) {
String path = MediaStore.Images.Media.insertImage(UploadImage.this.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
// Processing and adding user to database from here ====================================
public void Prcoess(){
String userentered=code.getText().toString();
String sentcode = SignupActivity.Code;
setPhoto();
if(userentered.equals(sentcode) && encodedPhotoString!=null ){
new AddUserAsync().execute();
}
else {
Toast.makeText(getBaseContext(), "Oopps...Sorry...Upload Again", Toast.LENGTH_LONG).show();
}
}
public void setPhoto() {
// resize the image to store to database
myimage= getResizedBitmap(myimage,400,400);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byte_arr = stream.toByteArray();
encodedPhotoString = Base64.encodeToString(byte_arr, 0);
Log.e("photo string ", encodedPhotoString);
}
public class AddUserAsync extends AsyncTask<Void,Void,Void> {
JSONObject json = null;
String fromServer = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(UploadImage.this);
pDialog.setMessage("Creating Account...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
GenerateGCMID();
email= email.trim().toLowerCase();
//HashMap<String ,String> userDetails = new HashMap<>();
latitude = GPSTracker.getLatitude();
longitude = GPSTracker.getLongitude();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(50, TimeUnit.SECONDS)
.writeTimeout(50, TimeUnit.SECONDS)
.readTimeout(50, TimeUnit.SECONDS)
.build();
FormBody.Builder formBuilder = new FormBody.Builder() // Null pointer exception is thrown here
.add("ID",ID)
.add("Name",name)
.add("email",email)
.add("password",password)
.add("age",age)
.add("number",number)
.add("bloodgroup",bloodgroup)
.add("lat",latitude+"")
.add("longi",longitude+"")
.add("image",encodedPhotoString);
RequestBody formBody = formBuilder.build();
Request request = new Request.Builder()
.url("http://faceblood.website/blood_app/Adduser.php")
.post(formBody)
.build();
try {
Response response = client.newCall(request).execute();
String res = response.body().string();
json = new JSONObject(res);
fromServer = json.getString("added");
Log.e("stringtest",json.getString("added"));
// Do something with the response.
} catch (IOException e) {
Log.e("stringtest IO",e.toString());
e.printStackTrace();
} catch (JSONException e) {
Log.e("stringtest JSON",e.toString());
e.printStackTrace();
}
//json = new HttpCall().postForJSON("http://faceblood.website/blood_app/Adduser.php",userDetails);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Log.e("fromServer",fromServer);
if(fromServer.equals("addeduser")){
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}else {
Toast.makeText(getBaseContext(), "Network problem. Click again", Toast.LENGTH_LONG).show();
}
}
}
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
// Go to another activity on success ====================================
public void onSignupSuccess() {
// stop the service we got the latitude and longitude now
myimage.recycle();
myimage = null;
ImageUpload.setImageResource(0);
stopService(new Intent(this, GPSTracker.class));
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
// Resize the image ====================================
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
}
Hint
at okhttp3.FormBody$Builder.add(FormBody.java:110)
at ...UploadImage$AddUserAsync.doInBackground(UploadImage.java:203)
You have added a null value to the Form here (at line 203)
FormBody.Builder formBuilder = new FormBody.Builder()
.add("ID",ID)
.add("Name",name)
.add("email",email)
.add("password",password)
.add("age",age)
.add("number",number)
.add("bloodgroup",bloodgroup)
.add("lat",latitude+"")
.add("longi",longitude+"")
.add("image",encodedPhotoString);
Which I am guessing starts from either here, where you are doing another asynchronous request.
public void GenerateGCMID(){
GCMClientManager pushClientManager = new GCMClientManager(this, "921544902369");
pushClientManager.registerIfNeeded(new GCMClientManager.RegistrationCompletedHandler() {
#Override
public void onSuccess(String registrationId, boolean isNewRegistration) {
ID = registrationId;
Log.e("reg",ID);
}
#Override
public void onFailure(String ex) {
super.onFailure(ex);
}
});
}
Or here because static values are not how you pass data between Activities. You cannot "reach" for a EditText value from the current Activity to a different one.
// fetch user details ====================================
public void GetUserDetails(){
bloodgroup = SignupActivity.bloodgroup.toString();
name = SignupActivity.name.toString();
email = SignupActivity.email.toString();
password = SignupActivity.password.toString();
number = SignupActivity.number.toString();
age = SignupActivity.age.toString();
}
You can refer to How do I pass data between Activities
Related
I keep getting an an error when trying to call WowZa GoCoder SDK's PlayerActivity and I am unable to understand the cause. The error appears when mStreamPlayerView.play(mStreamPlayerConfig, statusCallback) is called. Would really appreciate help on where i am going wrong
vodFragment.java
public class vodFragment extends Fragment {
private int mColumnCount = 1;
ListView videoView;
ArrayList <Vidoes> videoList;
private static String value;
String videoName;
String url = "http://192.168.43.149/twende/channelVOD.php";
public vodFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().setTitle(value);
}
View view = inflater.inflate(R.layout.fragment_vod_list, container, false);
videoView = (ListView) view.findViewById(R.id.listView);
videoList = new ArrayList<Vidoes>();
JSONObject channelInfo = new JSONObject();
try {
channelInfo.put("channelName", value);
channelInfo.put("channelOwner", "dan");
postJSONObject(url,channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
public static void setChannel(String channel){
value = channel;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void postJSONObject(final String myurl, final JSONObject parameters) {
class postJSONObject extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoVodView(s);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
HttpURLConnection conn = null;
try {
StringBuffer response = null;
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("responseCode" + responseCode);
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
postJSONObject postJSONObject = new postJSONObject();
postJSONObject.execute();
}
private void loadIntoVodView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
final String[] videos = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
videos[i] = removeExtension(obj.getString("title"));
Vidoes vidoe = new Vidoes();
vidoe.setTitle(videos[i]);
videoList.add(vidoe);
}
VideoListAdapter adapter = new VideoListAdapter(getActivity(), R.layout.vodparsedata, videoList);
videoView.setAdapter(adapter);
videoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
videoName = Arrays.asList(videos).get(position);
Intent intent = new Intent(getActivity(), PlayerActivity.class);
String message = videoName+".mp4";
intent.putExtra("videoName", message);
startActivity(intent);
System.out.println("arr: " + Arrays.asList(videos).get(position));
}
});
}
public static String removeExtension(String fileName) {
if (fileName.indexOf(".") > 0) {
return fileName.substring(0, fileName.lastIndexOf("."));
} else {
return fileName;
}
}
}
PlayerActivity.java
public class PlayerActivity extends GoCoderSDKActivityBase {
final private static String TAG = PlayerActivity.class.getSimpleName();
String videoName;
private WOWZPlayerView mStreamPlayerView = null;
private WOWZPlayerConfig mStreamPlayerConfig = new WOWZPlayerConfig();
private MultiStateButton mBtnPlayStream = null;
private MultiStateButton mBtnSettings = null;
private MultiStateButton mBtnMic = null;
private MultiStateButton mBtnScale = null;
private SeekBar mSeekVolume = null;
private ProgressDialog mBufferingDialog = null;
private StatusView mStatusView = null;
private TextView mHelp = null;
private TimerView mTimerView = null;
private ImageButton mStreamMetadata = null;
private boolean mUseHLSPlayback = false;
private WOWZPlayerView.PacketThresholdChangeListener packetChangeListener = null;
private VolumeChangeObserver mVolumeSettingChangeObserver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_player);
mRequiredPermissions = new String[]{};
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
videoName= null;
} else {
videoName= extras.getString("videoName");
}
} else {
videoName= (String) savedInstanceState.getSerializable("videoName");
}
System.out.print(videoName);
mStreamPlayerConfig.setIsPlayback(true);
mStreamPlayerConfig.setHostAddress("192.168.43.149");
mStreamPlayerConfig.setApplicationName("Dark Souls 2 Channel");
mStreamPlayerConfig.setStreamName(videoName);
mStreamPlayerConfig.setPortNumber(1935);
mStreamPlayerView = (WOWZPlayerView) findViewById(R.id.vwStreamPlayer);
mBtnPlayStream = (MultiStateButton) findViewById(R.id.ic_play_stream);
mBtnSettings = (MultiStateButton) findViewById(R.id.ic_settings);
mBtnMic = (MultiStateButton) findViewById(R.id.ic_mic);
mBtnScale = (MultiStateButton) findViewById(R.id.ic_scale);
mTimerView = (TimerView) findViewById(R.id.txtTimer);
mStatusView = (StatusView) findViewById(R.id.statusView);
mStreamMetadata = (ImageButton) findViewById(R.id.imgBtnStreamInfo);
mHelp = (TextView) findViewById(R.id.streamPlayerHelp);
mSeekVolume = (SeekBar) findViewById(R.id.sb_volume);
WOWZStatusCallback statusCallback = new StatusCallback();
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
mTimerView.setVisibility(View.GONE);
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
if (sGoCoderSDK != null) {
/*
Packet change listener setup
*/
final PlayerActivity activity = this;
packetChangeListener = new WOWZPlayerView.PacketThresholdChangeListener() {
#Override
public void packetsBelowMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have fallen below threshold "+packetCount+"... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have fallen below threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void packetsAboveMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have risen above threshold "+packetCount+" ... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have risen above threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
};
mStreamPlayerView.setShowAllNotificationsWhenBelowThreshold(false);
mStreamPlayerView.setMinimumPacketThreshold(20);
mStreamPlayerView.registerPacketThresholdListener(packetChangeListener);
///// End packet change notification listener
mTimerView.setTimerProvider(new TimerView.TimerProvider() {
#Override
public long getTimecode() {
return mStreamPlayerView.getCurrentTime();
}
#Override
public long getDuration() {
return mStreamPlayerView.getDuration();
}
});
mSeekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(progress);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// listen for volume changes from device buttons, etc.
mVolumeSettingChangeObserver = new VolumeChangeObserver(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mVolumeSettingChangeObserver);
mVolumeSettingChangeObserver.setVolumeChangeListener(new VolumeChangeObserver.VolumeChangeListener() {
#Override
public void onVolumeChanged(int previousLevel, int currentLevel) {
if (mSeekVolume != null)
mSeekVolume.setProgress(currentLevel);
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(currentLevel);
}
}
});
mBtnScale.setState(mStreamPlayerView.getScaleMode() == WOWZMediaConfig.FILL_VIEW);
// The streaming player configuration properties
mStreamPlayerConfig = new WOWZPlayerConfig();
mBufferingDialog = new ProgressDialog(this);
mBufferingDialog.setTitle(R.string.status_buffering);
mBufferingDialog.setMessage(getResources().getString(R.string.msg_please_wait));
mBufferingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
cancelBuffering(dialogInterface);
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onMetaData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
String meta = "";
if(eventParams!=null)
meta = eventParams.toString();
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+meta);
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onStatus", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+eventParams.toString());
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onTextData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> "+eventName+" = "+eventParams.get("text"));
return null;
}
});
} else {
mHelp.setVisibility(View.GONE);
mStatusView.setErrorMessage(WowzaGoCoder.getLastError().getErrorDescription());
}
}
#Override
protected void onDestroy() {
if (mVolumeSettingChangeObserver != null)
getApplicationContext().getContentResolver().unregisterContentObserver(mVolumeSettingChangeObserver);
super.onDestroy();
}
/**
* Android Activity class methods
*/
#Override
protected void onResume() {
super.onResume();
syncUIControlState();
}
#Override
protected void onPause() {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
// Wait for the streaming player to disconnect and shutdown...
mStreamPlayerView.getCurrentStatus().waitForState(WOWZState.IDLE);
}
super.onPause();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public boolean isPlayerConfigReady()
{
return false;
}
/*
Click handler for network pausing
*/
public void onPauseNetwork(View v)
{
Button btn = (Button)findViewById(R.id.pause_network);
if(btn.getText().toString().trim().equalsIgnoreCase("pause network")) {
WOWZLog.info("Pausing network...");
btn.setText("Unpause Network");
mStreamPlayerView.pauseNetworkStack();
}
else{
WOWZLog.info("Unpausing network... btn.getText(): "+btn.getText());
btn.setText("Pause Network");
mStreamPlayerView.unpauseNetworkStack();
}
}
/**
* Click handler for the playback button
*/
public void onTogglePlayStream(View v) {
if (mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
} else if (mStreamPlayerView.isReadyToPlay()) {
if(!this.isNetworkAvailable()){
displayErrorDialog("No internet connection, please try again later.");
return;
}
// if(!this.isPlayerConfigReady()){
// displayErrorDialog("Please be sure to include a host, stream, and application to playback a stream.");
// return;
// }
mHelp.setVisibility(View.GONE);
WOWZStreamingError configValidationError = mStreamPlayerConfig.validateForPlayback();
if (configValidationError != null) {
mStatusView.setErrorMessage(configValidationError.getErrorDescription());
} else {
// Set the detail level for network logging output
mStreamPlayerView.setLogLevel(mWZNetworkLogLevel);
// Set the player's pre-buffer duration as stored in the app prefs
float preBufferDuration = GoCoderSDKPrefs.getPreBufferDuration(PreferenceManager.getDefaultSharedPreferences(this));
mStreamPlayerConfig.setPreRollBufferDuration(preBufferDuration);
// Start playback of the live stream
mStreamPlayerView.play(mStreamPlayerConfig, this);
}
}
}
/**
* WOWZStatusCallback interface methods
*/
#Override
public synchronized void onWZStatus(WOWZStatus status) {
final WOWZStatus playerStatus = new WOWZStatus(status);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
WOWZStatus status = new WOWZStatus(playerStatus.getState());
switch(playerStatus.getState()) {
case WOWZPlayerView.STATE_PLAYING:
// Keep the screen on while we are playing back the stream
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mStreamPlayerConfig.getPreRollBufferDuration() == 0f) {
mTimerView.startTimer();
}
// Since we have successfully opened up the server connection, store the connection info for auto complete
GoCoderSDKPrefs.storeHostConfig(PreferenceManager.getDefaultSharedPreferences(PlayerActivity.this), mStreamPlayerConfig);
// Log the stream metadata
WOWZLog.debug(TAG, "Stream metadata:\n" + mStreamPlayerView.getMetadata());
break;
case WOWZPlayerView.STATE_READY_TO_PLAY:
// Clear the "keep screen on" flag
WOWZLog.debug(TAG, "STATE_READY_TO_PLAY player activity status!");
if(playerStatus.getLastError()!=null)
displayErrorDialog(playerStatus.getLastError());
playerStatus.clearLastError();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mTimerView.stopTimer();
break;
case WOWZPlayerView.STATE_PREBUFFERING_STARTED:
WOWZLog.debug(TAG, "Dialog for buffering should show...");
showBuffering();
break;
case WOWZPlayerView.STATE_PREBUFFERING_ENDED:
WOWZLog.debug(TAG, "Dialog for buffering should stop...");
hideBuffering();
// Make sure player wasn't signaled to shutdown
if (mStreamPlayerView.isPlaying()) {
mTimerView.startTimer();
}
break;
default:
break;
}
syncUIControlState();
}
});
}
#Override
public synchronized void onWZError(final WOWZStatus playerStatus) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
displayErrorDialog(playerStatus.getLastError());
syncUIControlState();
}
});
}
public void onToggleMute(View v) {
mBtnMic.toggleState();
if (mStreamPlayerView != null)
mStreamPlayerView.mute(!mBtnMic.isOn());
mSeekVolume.setEnabled(mBtnMic.isOn());
}
public void onToggleScaleMode(View v) {
int newScaleMode = mStreamPlayerView.getScaleMode() == WOWZMediaConfig.RESIZE_TO_ASPECT ? WOWZMediaConfig.FILL_VIEW : WOWZMediaConfig.RESIZE_TO_ASPECT;
mBtnScale.setState(newScaleMode == WOWZMediaConfig.FILL_VIEW);
mStreamPlayerView.setScaleMode(newScaleMode);
}
public void onStreamMetadata(View v) {
WOWZDataMap streamMetadata = mStreamPlayerView.getMetadata();
WOWZDataMap streamStats = mStreamPlayerView.getStreamStats();
// WOWZDataMap streamConfig = mStreamPlayerView.getStreamConfig().toDataMap();
WOWZDataMap streamConfig = new WOWZDataMap();
WOWZDataMap streamInfo = new WOWZDataMap();
streamInfo.put("- Stream Statistics -", streamStats);
streamInfo.put("- Stream Metadata -", streamMetadata);
//streamInfo.put("- Stream Configuration -", streamConfig);
DataTableFragment dataTableFragment = DataTableFragment.newInstance("Stream Information", streamInfo, false, false);
getFragmentManager().beginTransaction()
.add(android.R.id.content, dataTableFragment)
.addToBackStack("metadata_fragment")
.commit();
}
public void onSettings(View v) {
// Display the prefs fragment
GoCoderSDKPrefs.PrefsFragment prefsFragment = new GoCoderSDKPrefs.PrefsFragment();
prefsFragment.setFixedSource(true);
prefsFragment.setForPlayback(true);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, prefsFragment)
.addToBackStack(null)
.commit();
}
private void syncUIControlState() {
boolean disableControls = (!(mStreamPlayerView.isReadyToPlay() || mStreamPlayerView.isPlaying()) || sGoCoderSDK == null);
if (disableControls) {
mBtnPlayStream.setEnabled(false);
mBtnSettings.setEnabled(false);
mSeekVolume.setEnabled(false);
mBtnScale.setEnabled(false);
mBtnMic.setEnabled(false);
mStreamMetadata.setEnabled(false);
} else {
mBtnPlayStream.setState(mStreamPlayerView.isPlaying());
mBtnPlayStream.setEnabled(true);
if (mStreamPlayerConfig.isAudioEnabled()) {
mBtnMic.setVisibility(View.VISIBLE);
mBtnMic.setEnabled(true);
mSeekVolume.setVisibility(View.VISIBLE);
mSeekVolume.setEnabled(mBtnMic.isOn());
mSeekVolume.setProgress(mStreamPlayerView.getVolume());
} else {
mSeekVolume.setVisibility(View.GONE);
mBtnMic.setVisibility(View.GONE);
}
mBtnScale.setVisibility(View.VISIBLE);
mBtnScale.setVisibility(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled() ? View.VISIBLE : View.GONE);
mBtnScale.setEnabled(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled());
mBtnSettings.setEnabled(!mStreamPlayerView.isPlaying());
mBtnSettings.setVisibility(mStreamPlayerView.isPlaying() ? View.GONE : View.VISIBLE);
mStreamMetadata.setEnabled(mStreamPlayerView.isPlaying());
mStreamMetadata.setVisibility(mStreamPlayerView.isPlaying() ? View.VISIBLE : View.GONE);
}
}
private void showBuffering() {
try {
if (mBufferingDialog == null) return;
mBufferingDialog.show();
}
catch(Exception ex){}
}
private void cancelBuffering(DialogInterface dialogInterface) {
if(mStreamPlayerConfig.getHLSBackupURL()!=null || mStreamPlayerConfig.isHLSEnabled()){
mStreamPlayerView.stop(true);
}
else if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop(true);
}
}
private void hideBuffering() {
if (mBufferingDialog.isShowing())
mBufferingDialog.dismiss();
}
#Override
public void syncPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mWZNetworkLogLevel = Integer.valueOf(prefs.getString("wz_debug_net_log_level", String.valueOf(WOWZLog.LOG_LEVEL_DEBUG)));
mStreamPlayerConfig.setIsPlayback(true);
if (mStreamPlayerConfig != null)
GoCoderSDKPrefs.updateConfigFromPrefsForPlayer(prefs, mStreamPlayerConfig);
}
private class StatusCallback implements WOWZStatusCallback {
#Override
public void onWZStatus(WOWZStatus wzStatus) {
}
#Override
public void onWZError(WOWZStatus wzStatus) {
}
}
}
The error I get is;
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wowza.gocoder.sdk.sampleapp/com.wowza.gocoder.sdk.sampleapp.PlayerActivity}: java.lang.RuntimeException: Invalid surface: null
You start the stream in onCreate. At this time the Surface used by WOWZPlayerView is not ready yet and the app crashes with the 'Invalid surface' error.
If you look at the sample test in the GoCoder SDK, the playback is started when the user clicks a button. Eg. when the Surface is valid.
Create a button and move your 'mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);' to the button.onClick.
Or ... use any GoCoder SDK v1.7 and more recent.
Please, let me know if I can help any further.
Thanks
I want to Upload file to server by selecting the file from file manager So I have opened file manager by clicking on Button using this code,
button_upload_attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] galleryPermissions = {android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (EasyPermissions.hasPermissions(CIBILCaptureandUPLOAD.this, galleryPermissions)) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
} else {
EasyPermissions.requestPermissions(this, "Access for storage",
101, galleryPermissions);
}
}
});
and onActivityResult method i have done something like this to get path of the file and had make UploadToserver function for uploading
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//ImagesData = data;
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
Uri contentUri=data.getData();
Log.e("bbbbbbbbbbbbbb", contentUri.toString());
if(contentUri.toString().endsWith(".png")||contentUri.toString().endsWith("jpg") ||
contentUri.toString().endsWith(".pdf")){
photoFile= new File(contentUri.getPath());
if (photoFile.exists()) {
Log.e("photoFile", "File Exists");
}
if (photoFile != null) {
new AsyncTask<String, String, File>() {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
Log.e("PreExecute", "Compressing");
}
#Override
protected File doInBackground(String[] params) {
return photoFile;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result != null) {
new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
}
}
}.execute("");
}
}else {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri,
filePathColumn, null, null, null);
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = "";
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
Log.e("PATH", filePath);
photoFile = new File(filePath);
if (photoFile.exists()) {
Log.e("photoFile", "File Exists");
}
if (photoFile != null) {
new AsyncTask<String, String, File>() {
ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Compressing...");
Log.e("PreExecute", "Compressing");
}
#Override
protected File doInBackground(String[] params) {
return photoFile;
}
#Override
protected void onPostExecute(File result) {
pd.dismiss();
if (result != null) {
new CIBILCaptureandUPLOAD.UploadFileToServer().execute(result);
}
}
}.execute("");
}
}
}
It works well in other devices but in samsung devices i have got
java.io.FileNotFoundException: /document/primary:Xender/other/When Strangers Meet_ 3 in 1 Box - John Harker.pdf: open failed: ENOENT (No such file or directory)
And my upload code is
private class UploadFileToServer extends AsyncTask {
private static final String TAG = "UploadFileToServer";
// private ProgressBar progressBar;
// private String filePath = null;
// private TextView txtPercentage;
private ProgressDialog pd;
long totalSize = 0;
#Override
protected void onPreExecute() {
// setting progress bar to zero
// progressBar.setProgress(0);
pd = ProgressDialog.show(CIBILCaptureandUPLOAD.this, "", "Loading...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
pd.setMessage("Loading..." + progress[0]);
// progressBar.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(File... params) {
return uploadFile1(params[0]);
}
#SuppressWarnings("deprecation")
private String uploadFile1(File file) {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppUtill.URL_CIBIL_imageupload);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = file;// new File(filePath);
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("mid", new StringBody(memberid));
entity.addPart("did", new StringBody("0"));
entity.addPart("fid", new StringBody(formtypeid));
if (app_loadid == null) {
SharedPreferences sharedPreferences = getSharedPreferences("LID", MODE_PRIVATE);
app_loadid = sharedPreferences.getString("lid", "");
entity.addPart("lid", new StringBody(app_loadid));
} else {
entity.addPart("lid", new StringBody(app_loadid));
}
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode +statusCode");
if (statusCode == 200) {
// Server response
System.out.println("statusCode +statusCode");
responseString = EntityUtils.toString(r_entity);
String success = String.valueOf(responseString.contains("1"));
if (success.matches("true")) {
uploadedFileCount++;
} else {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "File not uploaded. Please upload again...", Toast.LENGTH_SHORT).show();
}
});
}
} else {
responseString = "Error occurred! Http Status Code: " + statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
pd.dismiss();
if (uploadedFileCount == MAX_COUNT) {
AlertDialog.Builder alert = new AlertDialog.Builder(CIBILCaptureandUPLOAD.this);
alert.setTitle(R.string.app_name);
alert.setMessage("Reach to max upload limit");
alert.setCancelable(false);
alert.setPositiveButton("OK", null);
alert.create().show();
}
// showing the server response in an alert dialog
showAlert(result);
AppUtill.deleteFolderAndAllFile(CIBILCaptureandUPLOAD.this);
super.onPostExecute(result);
}
}
photoFile= new File(contentUri.getPath());
Have a look at the value of contentUri.getPath() and see that it is not a valid file system path.
Instead you should open an InputStream for the obtained uri and read the file content from the stream.
InputStream is = getContentResolver().openInputStream(contentUri);
I'm following this tutorial (http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/) to uploading photo. And I'm using header authentication in httppost. But, why when uploading didn't work.
I using 'org.apache.httpcomponents:httpmime:4.3.6' in my dependencies.
Anyone can help me.
This my Activity.
public class SendReportActivity extends Activity {
private static final String TAG = SendReportActivity.class.getSimpleName();
private String filePath = null;
private ImageView imgPreview;
private ProgressBar progressBar;
private TextView txtPercentage;
private Button btnUpload;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_report);
txtPercentage = (TextView) findViewById(R.id.txtPercentage);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnUpload = (Button) findViewById(R.id.btnKirim);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
Intent i = getIntent();
filePath = i.getStringExtra("filePath");
boolean isImage = i.getBooleanExtra("isImage", true);
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(isImage);
} else {
Toast.makeText(getApplicationContext(),
"Sorry, file path is missing!", Toast.LENGTH_LONG).show();
}
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// uploading the file to server
new UploadFileToServer().execute();
}
});
}
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throws OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
imgPreview.setImageBitmap(bitmap);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(AppConfig.URL_LAPOR);
httppost.addHeader("Authorization", "Basic " +
Base64.encodeToString((AppConfig.USER_API + ":" + AppConfig.PASSWORD_API).getBytes(), Base64.DEFAULT));
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
entity.addPart("data_des", new StringBody("OK"));
entity.addPart("data_upload", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
Log.e(TAG, "Response from server: " + result);
// showing the server response in an alert dialog
showAlert(result);
super.onPostExecute(result);
}
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
This error log.
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:278)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NoClassDefFoundError: org.apache.http.Consts
at org.apache.http.entity.mime.content.StringBody.<init>(StringBody.java:148)
at com.company.report.activity.SendReportActivity$UploadFileToServer.uploadFile(SendReportActivity.java:232)
at com.company.report.activity.SendReportActivity$UploadFileToServer.doInBackground(SendReportActivity.java:208)
at com.company.report.activity.SendReportActivity$UploadFileToServer.doInBackground(SendReportActivity.java:186)
at android.os.AsyncTask$2.call(AsyncTask.java:264)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:856)
This is my activity code, when click on capture picture button, it will load camera from your phone. after i take a picture with camera, the picture will show at the imageView. Then i will click upload image picture button to upload my picture to server. Here the problem i faced, the code works well on all android version 4.4 and below, when i test this code with android 5.0, the picture taken from camera wasn't show on the imageView. I had tried many solution and yet keep fail. Can anyone help me with this? thank you.
Activity code
public class TestUpload extends Activity implements OnItemSelectedListener {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello camera";
private Uri fileUri;
private ImageView imgPreview;
private Button btnCapturePicture, btnUploadImage;
private EditText itemname;
private EditText description;
private EditText price;
private EditText contact;
private String randNum, uname;
Random random = new Random();
private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STR_LENGTH = 12;
private Spinner spinCat, spinLoc;
private String [] Category = {"IT Gadgets","Men Fashion","Women Fashion","Beauty","Sports","Cars and Motors","Furnitures","Music Instrument","Books","Property","Photography","Games and Toys","kids and Baby","Others"};
private String [] Location = {"Kuala Lumpur","Melacca","Johor","Selangor","Kelantan","Kedah","Negeri Sembilan",
"Pahang","Perak","Perlis","Penang","Sabah","Sarawak","Terengganu"};
private static final String TAG_SUCCESS = "success";
JSONParser2 jsonParser2 = new JSONParser2();
private static String url_create_image = "http://gemini888.tk/GP_trade_api_v2/image_connect/create_product.php";
private SweetAlertDialog pDialog;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_test);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#96ead7")));
ab.setDisplayHomeAsUpEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btn_camera);
btnUploadImage = (Button) findViewById(R.id.btn_upload);
itemname = (EditText) findViewById(R.id.input_upload_item_name);
description = (EditText) findViewById(R.id.input_item_desc);
price = (EditText) findViewById(R.id.upload_input_item_price);
contact = (EditText) findViewById(R.id.input_contact);
spinCat = (Spinner) findViewById(R.id.spin_category);
spinLoc = (Spinner) findViewById(R.id.spin_location);
ArrayAdapter<String> adapter_Category = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Category);
ArrayAdapter<String> adapter_Location = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Location);
adapter_Category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_Location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCat.setAdapter(adapter_Category);
spinLoc.setAdapter(adapter_Location);
spinCat.setOnItemSelectedListener(this);
spinLoc.setOnItemSelectedListener(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
//timeStamp = new SimpleDateFormat ("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
randNum = getRandomString();
//capture image button click event
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//capture image
captureImage();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//uploading the file to server
new UploadFileToServer().execute();
}
});
}
//capturing Camera image will lunch camera app request image capture
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Start image capture intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
//Receiving activity result method will be called after closing the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//if the result i capture image
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
//success capture image, display it on imageview
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
//user cancel image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
//failed to capture image
Toast.makeText(getApplicationContext(), "Sorry, failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
//Display image from a path to imageview
private void previewCapturedImage() {
imgPreview.setVisibility(View.VISIBLE);
//bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
//downsize image as it throws Outofmemory execption for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
//store the file url as it will be null after returning from camera app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save file url in bundle as it will be null on screen orientation change
outState.putParcelable("file_uri", fileUri);
}
//restore the fileUri again
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the Urifile
fileUri = savedInstanceState.getParcelable("file_uri");
}
//create file Uri to store image
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
//returning image
private File getOutputMediaFile(int type) {
//External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), UserFunctions.IMAGE_DIRECTORY_NAME);
//create the storage directory if it does not exist
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Failed create" + UserFunctions.IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
//Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + uname + randNum + ".jpg");
} else {
return null;
}
return mediaFile;
}
//upload image to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new SweetAlertDialog(TestUpload.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Picture uploading, please wait..");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void...params) {
String iname = itemname.getText().toString();
String des = description.getText().toString();
String iprice = price.getText().toString();
String icontact = contact.getText().toString();
String cat = spinCat.getSelectedItem().toString();
String loc = spinLoc.getSelectedItem().toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("name", iname));
param.add(new BasicNameValuePair("description", des));
param.add(new BasicNameValuePair("price", iprice));
param.add(new BasicNameValuePair("username", uname));
param.add(new BasicNameValuePair("category", cat));
param.add(new BasicNameValuePair("location", loc));
param.add(new BasicNameValuePair("timestamp", randNum));
param.add(new BasicNameValuePair("contact", icontact));
JSONObject json = jsonParser2.makeHttpRequest(url_create_image,
"POST", param);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Create Response", "success");
} else {
// failed to create product
Toast.makeText(getApplicationContext(),"failed",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return uploadFile();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UserFunctions.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
setProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(fileUri.getPath());
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("http://gemini888.tk"));
entity.addPart("email", new StringBody("thegemini888#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
public String getRandomString() {
StringBuffer randStr = new StringBuffer();
for (int i =0; i<RANDOM_STR_LENGTH; i++) {
int number = getRandomNumber();
char ch = _CHAR.charAt(number);
randStr.append(ch);
}
return randStr.toString();
}
private int getRandomNumber() {
int randomInt = 0;
randomInt = random.nextInt(_CHAR.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinCat.setSelection(position);
String CatList = (String) spinCat.getSelectedItem();
CatList.toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
in captureImage() method try this.
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
//Start image capture intent
}
//first of all create a directory to store your captured Images
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/PGallery");
if (!myDir.exists()) {
myDir.mkdirs();
}
//Give name to your captured Image
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss",java.util.Locale.getDefault());
Date date = new Date();
String sDate = formatter.format(date);
imageName = "PRAVA"+sDate+".jpg";
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filePath = new File(myDir,imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
catch (ActivityNotFoundException e) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
On Actvity Result:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
ImagePath = filePath.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(ImagePath, bitmapOptions);
ImageView mImageView = (ImageView) findViewById(R.id.ivCamreaPic);
mImageView.setImageBitmap(bitmap);
}
I have been following a tutorial (http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/) in order to make a listview display nearest restaurant to your location in radius of 5km.
However i keep getting an error, in my Runnable it says that the status variable is null. I don't really understand why this error pops up. Can you guys give me a short explanation and help find a solution??
PlacesList.java
public class PlacesList implements Serializable {
public String status;
public List<Place> results;
}
DisplayLocations.java
public class DisplayLocations extends Activity {
boolean isInternetPresent = false;
ConnectionDetector cd;
GooglePlaces googlePlaces;
PlacesList nearPlaces;
GPSTracker gps;
Button shownOnMap;
ProgressDialog pDialog;
ListView lv;
ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
public static String KEY_REFERENCE = "reference";
public static String KEY_NAME = "name";
public static String KEY_VICINITY = "vicinity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_locations);
cd = new ConnectionDetector(getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
if(!isInternetPresent){
Toast.makeText(getApplicationContext(), "Get a working connection", Toast.LENGTH_SHORT).show();
return;
}
gps = new GPSTracker(DisplayLocations.this);
if(gps.canGetLocation()){
}else{
gps.showSettingsAlert();
}
lv = (ListView)findViewById(R.id.list);
shownOnMap = (Button)findViewById(R.id.btn_show_map);
new LoadPlaces().execute();
shownOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
Intent i = new Intent(getApplicationContext(), PlacesMapActivity.class);
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
i.putExtra("near_places", nearPlaces);
startActivity(i);
*/
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String reference = ((TextView) findViewById(R.id.reference)).getText().toString();
/*
Intent in = new Intent(getApplicationContext(), SingePlaceActivity.class);
in.putExtra(KEY_REFERENCE, reference);
startActivity(in);
*/
}
});
}
class LoadPlaces extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayLocations.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
googlePlaces = new GooglePlaces();
try{
String types = "cafe|restaurant";
double radius = 5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
String status = nearPlaces.status;
if (status.equals("OK")){
if(nearPlaces.results != null){
for (Place p : nearPlaces.results){
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_REFERENCE, p.reference);
map.put(KEY_NAME, p.name);
placesListItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(DisplayLocations.this, placesListItems, R.layout.location_listview_item,
new String[]{KEY_REFERENCE, KEY_NAME}, new int[]{R.id.reference, R.id.name});
lv.setAdapter(adapter);
}
}
else if(status.equals("ZERO_RESULTS")){
// Zero results found
Toast.makeText(getApplicationContext(), "No Results", Toast.LENGTH_SHORT);
}
else if(status.equals("UNKNOWN_ERROR"))
{
Toast.makeText(getApplicationContext(), "Unknown error", Toast.LENGTH_SHORT);
}
else if(status.equals("OVER_QUERY_LIMIT"))
{
Toast.makeText(getApplicationContext(), "Query limit reached !", Toast.LENGTH_SHORT);
}
else if(status.equals("REQUEST_DENIED"))
{
Toast.makeText(getApplicationContext(), "Request denied", Toast.LENGTH_SHORT);
}
else if(status.equals("INVALID_REQUEST"))
{
Toast.makeText(getApplicationContext(), "Invalid request", Toast.LENGTH_SHORT);
}
else
{
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT);
}
}
});
}
}
#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_display_locations, 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);
}
}
GooglePlaces.java
public class GooglePlaces {
private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
private final String API_KEY = "AIzaSyCxY1X7hC7SOab7V3GbWd1u42fGThgYOhg";
//GooglePlaces search URL
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_TEXT_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?";
private static final String PLACES_DETAILS_URL = "https://maps.googleapis.com/maps/api/place/details/json?";
private double mLatitiude;
private double mLongitude;
private double mRadius;
public PlacesList search(double latitude, double longitude, double radius, String types) throws Exception{
this.mLatitiude = latitude;
this.mLongitude = longitude;
this.mRadius = radius;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", mLatitiude + "," + mLongitude);
request.getUrl().put("radius", mRadius); // in meters
request.getUrl().put("sensor", "false");
if (types != null)
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
public PlaceDetails getPlaceDetails(String reference) throws Exception{
try{
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory.buildGetRequest(new GenericUrl(PLACES_DETAILS_URL));
request.getUrl().put("reference", reference);
request.getUrl().put("key", API_KEY);
request.getUrl().put("sensor",false);
PlaceDetails place = request.execute().parseAs(PlaceDetails.class);
return place;
}catch (HttpResponseException e){
throw e;
}
}
public static HttpRequestFactory createRequestFactory(final HttpTransport transport){
return transport.createRequestFactory(new HttpRequestInitializer() {
#Override
public void initialize(HttpRequest request) throws IOException {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setUserAgent("Application Test");
request.setHeaders(httpHeaders);
JsonObjectParser parser = new JsonObjectParser(new JsonFactory() {
#Override
public JsonParser createJsonParser(InputStream in) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(InputStream in, Charset charset) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(String value) throws IOException {
return null;
}
#Override
public JsonParser createJsonParser(Reader reader) throws IOException {
return null;
}
#Override
public JsonGenerator createJsonGenerator(OutputStream out, Charset enc) throws IOException {
return null;
}
#Override
public JsonGenerator createJsonGenerator(Writer writer) throws IOException {
return null;
}
});
request.setParser(parser);
}
});
}
}
Line 132 of DisplayLocations.java is :
String status = nearPlaces.status;
This is the stacktrace :
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.example.dell.exampleapplication.PlacesList.status' on a null object reference
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces$1.run(DisplayLocations.java:132)
at android.app.Activity.runOnUiThread(Activity.java:5517)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:129)
at com.example.dell.exampleapplication.DisplayLocations$LoadPlaces.onPostExecute(DisplayLocations.java:98)
at android.os.AsyncTask.finish(AsyncTask.java:632)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5834)
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:1388)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Any help and explanation would be appreciated.
Thanks, have a nice day.
EDIT:
nearPlaces.status = ... (the status: probably from GooglePlaces) in doInBackGround
then you can do:
String status = nearPlaces.status; in onPostExecute
Add the line
#Override
protected String doInBackground(String... params) {
googlePlaces = new GooglePlaces();
try{
String types = "cafe|restaurant";
double radius = 5000;
nearPlaces = googlePlaces.search(gps.getLatitude(), gps.getLongitude(), radius, types);
nearPlaces.status = "OK"; //Add this line for testing, your code should work now, because status is not NULL anymore.
}catch (Exception e){
e.printStackTrace();
}
return null;
}