Making remote server calls in an Android application - java

I've made an apache thrift server and I have a service which contains several functions.
I'm trying to figure out what is the best way to make calls to the remote server from my android application.
My problem is that I can't make calls from the MainActivity thread (the main thread) - and I need to use most of the remote functions in my main activity methods.
I tried to make a static class with a static member called "Server" equals to the server object, and I set it in another thread and then I tried to call it in the main thread (the main activity class) - but I had errors because of jumping from one thread to another..
To be more specified I want something like that:
public class MainActivity extends Activity {
private service.Client myService;
#Override
protected void onCreate(Bundle savedInstanceState) {
..
... Some stuff that define myService (In a new thread ofcourse) ...
}
...
private void MyFunc1() {
myService.Method1();
}
private void MyFunc2() {
myService.Method2();
}
private void MyFunc3() {
myService.Method3();
}
}

I've got a library for talking to REST APIs. Feel free to slice, dice, and re-use: https://github.com/nedwidek/Android-Rest-API
The code is BSD or GPL.
Here's how I use what I have (I've trimmed MainActivity a bit, hopefully not too much):
package com.hatterassoftware.voterguide.api;
import java.util.HashMap;
public class GoogleCivicApi {
protected final String baseUrl = "https://www.googleapis.com/civicinfo/us_v1/";
protected String apiKey = "AIzaSyBZIP5uY_fMF35SVVrytpKgHtppBbj8J0I";
public static final String DATE_FORMAT = "yyyy-MM-dd";
protected static HashMap<String, String> headers;
static {
headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
}
public String createUrl(String uri, HashMap<String, String> params) {
String url = baseUrl + uri + "?key=" + apiKey;
if (params != null) {
for (String hashKey: params.keySet()) {
url += hashKey + "=" + params.get(hashKey) + "&";
}
url = url.substring(0, url.length());
}
return url;
}
}
package com.hatterassoftware.voterguide.api;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.hatterassoftware.restapi.GetTask;
import com.hatterassoftware.restapi.HttpReturn;
import com.hatterassoftware.restapi.RestCallback;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.models.Election;
public class ElectionsQuery extends GoogleCivicApi implements RestCallback {
GetTask getTask;
ElectionCallback callback;
final String TAG = "ElectionQuery";
public ElectionsQuery(ElectionCallback callback) {
String url = this.createUrl("elections", null);
this.callback = callback;
Log.d(TAG, "Creating and executing task for: " + url);
getTask = new GetTask(url, this, null, null, null);
getTask.execute();
}
#Override
public void onPostSuccess() {
Log.d(TAG, "onPostSuccess entered");
}
#Override
public void onTaskComplete(HttpReturn httpReturn) {
Log.d(TAG, "onTaskComplete entered");
Log.d(TAG, "httpReturn.status = " + httpReturn.status);
if (httpReturn.content != null) Log.d(TAG, httpReturn.content);
if (httpReturn.restException != null) Log.d(TAG, "Exception in httpReturn", httpReturn.restException);
JsonParser parser = new JsonParser();
JsonElement electionArrayJson = ((JsonObject)parser.parse(httpReturn.content)).get("elections");
Log.d(TAG, electionArrayJson.toString());
Gson gson = new GsonBuilder().setDateFormat(GoogleCivicApi.DATE_FORMAT).create();
Election[] elections = gson.fromJson(electionArrayJson.toString(), Election[].class);
callback.retrievedElection(elections);
}
}
package com.hatterassoftware.voterguide;
import java.util.Calendar;
import java.util.List;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.hatterassoftware.voterguide.api.ElectionsQuery;
import com.hatterassoftware.voterguide.api.VoterInfoQuery;
import com.hatterassoftware.voterguide.api.callbacks.ElectionCallback;
import com.hatterassoftware.voterguide.api.callbacks.VoterInfoCallback;
import com.hatterassoftware.voterguide.api.models.Election;
import com.hatterassoftware.voterguide.api.models.VoterInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends SherlockFragmentActivity implements ElectionCallback, VoterInfoCallback {
private ProgressBar mProgressBar;
public Button submit;
public Spinner state;
public Spinner election;
public EditText address;
public EditText city;
public EditText zip;
private int count=0;
private Object lock = new Object();
private static final String TAG = "MainActivity";
public static final String VOTER_INFO = "com.hatterassoftware.voterguide.VOTER_INFO";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.home_progressBar);
Resources res = getResources();
SharedPreferences mPrefs = getApplicationSharedPreferences();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
try {
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!manager.isProviderEnabled(Context.LOCATION_SERVICE)) {
gpsButton.setClickable(false);
}
} catch(Exception e) {
Log.d(TAG, e.getMessage(), e);
gpsButton.setClickable(false);
gpsButton.setEnabled(false);
}
submit = (Button) findViewById(R.id.submit);
submit.setClickable(false);
submit.setEnabled(false);
state = (Spinner) findViewById(R.id.state);
election = (Spinner) findViewById(R.id.election);
address = (EditText) findViewById(R.id.streetAdress);
city = (EditText) findViewById(R.id.city);
zip = (EditText) findViewById(R.id.zip);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doSubmit();
}
});
gpsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLocate();
}
});
// Let's check for network connectivity before we get down to business.
if (Utils.isNetworkAvailable(this, true)) {
// Show the disclaimer on first run.
if(mPrefs.getBoolean("firstRun", true)) {
AlertDialog alert = new AlertDialog.Builder(this).create();
alert.setCancelable(false);
alert.setTitle(res.getString(R.string.welcome));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_dialog, null);
TextView alertContents = (TextView) layout.findViewById(R.id.custom_dialog_text);
alertContents.setMovementMethod(LinkMovementMethod.getInstance());
alertContents.setText(Html.fromHtml(res.getString(R.string.welcome_dialog_text)));
alert.setView(alertContents);
alert.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences mPrefs = getApplicationSharedPreferences();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean("firstRun", false);
editor.commit();
dialog.dismiss();
retrieveElections();
}
});
alert.show();
} else {
retrieveElections();
}
}
}
#Override
public void onResume() {
super.onResume();
// Let's check for network connectivity before we get down to business.
Utils.isNetworkAvailable(this, true);
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if (!(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))) {
Toast.makeText(this, "GPS is not available", 2).show();
ImageButton gpsButton = (ImageButton) findViewById(R.id.locate);
gpsButton.setClickable(false);
}
}
public SharedPreferences getApplicationSharedPreferences() {
Context mContext = this.getApplicationContext();
return mContext.getSharedPreferences("com.hatterassoftware.voterguide", MODE_PRIVATE);
}
private void showSpinner() {
synchronized(lock) {
count++;
mProgressBar.setVisibility(View.VISIBLE);
}
}
private void hideSpinner() {
synchronized(lock) {
count--;
if(count < 0) { // Somehow we're trying to hide it more times than we've shown it.
count=0;
}
if (count == 0) {
mProgressBar.setVisibility(View.INVISIBLE);
}
}
}
public void retrieveElections() {
Log.d(TAG, "Retrieving the elections");
showSpinner();
ElectionsQuery query = new ElectionsQuery(this);
}
#Override
public void retrievedElection(Election... elections) {
Log.d(TAG, "Retrieved the elections");
hideSpinner();
for (int i=0; i<elections.length; i++) {
Log.d(TAG, elections[i].toString());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, elections);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner spinner = (Spinner) this.findViewById(R.id.election);
spinner.setAdapter(arrayAdapter);
}
}

Related

How to get Extended advertising data using android app

So I am working on Nordic nrf52840 which is broadcasting extended advertising, thanks to the people on stackoverflow I can finally find my device, now the only function left is to dump extended advertising data to log, I found out that ScanResult contain may have contain the adv data I need but when I tried to dump it to log it show only {} why and how can I read adv data.
package com.example.tryble_scanner;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothLeScanner mBluetoothLeScanner = null;
public static final int REQUEST_BT_PERMISSIONS = 0;
public static final int REQUEST_BT_ENABLE = 1;
private boolean mScanning = false;
private Handler mHandler = null;
private ScanCallback mLeScanCallBack1 = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
//super.onScanResult(callbackType, result);
String data=ConverttoString(result.getScanRecord().getManufacturerSpecificData());
BluetoothDevice btdevice = result.getDevice();
Log.d("BLE", btdevice.getAddress());
Log.d("BLE",data);
}
#Override
public void onScanFailed(int errorCode) {
super.onScanFailed(errorCode);
Log.d("BLE", "error");
}
};
private ScanCallback mLeScanCallBack2=new ScanCallback() {
#Override
public void onScanResult(int callbackType, ScanResult result) {
Log.d("BLE","scan stop");
}
#Override
public void onScanFailed(int errorCode) {
Log.d("BLE","stop scan failed");
}
};
private BluetoothAdapter.LeScanCallback mLeScanCallBack3=new
BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnScan = (Button) findViewById(R.id.btnScan);
BluetoothManager bluetoothManager = getSystemService(BluetoothManager.class);
mBluetoothAdapter = bluetoothManager.getAdapter();
mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
this.mHandler = new Handler();
}
public void stop_scan(View view) {
Log.d("Ble","scan stop pressed");
// mBluetoothLeScanner.stopScan(mLeScanCallback2);
mBluetoothAdapter.getBluetoothLeScanner().stopScan(mLeScanCallBack2);
}
public void onBtnScan(View view) {
Log.i("Btn","get click");
checkBTPermission();
String[] names=new String[]{"Auden test"};
List<ScanFilter> filters=null;
if(names != null){
filters=new ArrayList<>();
for(String name:names){
ScanFilter filter=new ScanFilter.Builder().setDeviceName(name).build();
filters.add(filter);
}
}
ScanSettings scanSettings = new ScanSettings.Builder()
//.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
//.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
//.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
//.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT)
//.setReportDelay(0L)
.setLegacy(false)
.build();
if(mBluetoothLeScanner==null){
Log.i("BLE","could not get scanner");
}else{
mBluetoothLeScanner.startScan(filters,scanSettings,mLeScanCallBack1); //filters,scanSettings,mLeScanCallback
}
}
private void checkBTPermission(){
if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
int pc=this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
pc+=this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(pc!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}else {
Log.d("BLE","checkBT permission");
}
}
}
public static String ConverttoString (SparseArray<byte[]> array) {
if (array == null) {
return "null";
}
if (array.size() == 0) {
return "{}";
}
StringBuilder buffer = new StringBuilder();
buffer.append('{');
for (int i = 0; i < array.size(); ++i) {
buffer.append(array.keyAt(i)).append("=").append(Arrays.toString(array.valueAt(i)));
}
buffer.append('}');
Log.d("convert",buffer.toString());
return buffer.toString();
}
}

query.addListenerForSingleValueEvent won't run...?

i try to connect to firebase to get display_name and also profile_photo
for my post like instagram
like this one
example image
but when i run my app it says that i have nullPointerException on my variable
mUserAccountSettings cause my app won't run onDataChanged() or onDataCancelled()
function.
i already tried to get data from mUserAccountSettings for Profile class and actually it work perfectly but in ViewFragment class it won't work
it says :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jesslyn.foodylife, PID: 5655
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String
com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings.getProfile_photo()'
on a null object reference
at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.setupWidgets(ViewPostFragment.java:156)
at com.example.jesslyn.foodylife.FoodyLife.Utils.ViewPostFragment.onCreateView(ViewPostFragment.java:117)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2192)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1299)
at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
at android.os.Handler.handleCallback(Handler.java:742)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5544)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
E/MQSEventManagerDelegate: failed to get MQSService.
and this is my code in ViewFragment class:
package com.example.jesslyn.foodylife.FoodyLife.Utils;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.LoginFilter;
import android.util.EventLogTags;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.BottomNavigationViewHelper;
import com.example.jesslyn.foodylife.FoodyLife.Utils.FirebaseMethods;
import com.example.jesslyn.foodylife.FoodyLife.Utils.GridImageAdapter;
import com.example.jesslyn.foodylife.FoodyLife.Utils.SquareImageView;
import com.example.jesslyn.foodylife.FoodyLife.Utils.UniversalImageLoader;
import com.example.jesslyn.foodylife.FoodyLife.models.Photo;
import com.example.jesslyn.foodylife.FoodyLife.models.UserAccountSettings;
import com.example.jesslyn.foodylife.R;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GetTokenResult;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import junit.framework.Test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import java.util.concurrent.Executor;
/**
* Created by Jesslyn on 12/4/2017.
*/
public class ViewPostFragment extends Fragment {
private static final String TAG = "ViewPostFragment";
private SquareImageView mPostImage;
private BottomNavigationViewEx bottomNavigationViewEx;
private TextView mBackLabel, mCaption, mUsername, mTimeStamp;
private ImageView mBackArrow, mEllipses, mProfileImage;
private RatingBar mStars;
private String photoUrl;
private Photo mPhoto;
private int mActivityNumber = 0;
private String photoUsername = "";
private String profilePhotoUrl = "";
private UserAccountSettings mUserAccountSettings;
// firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
private String userID;
public ViewPostFragment() {
super();
setArguments(new Bundle());
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_view_post, container, false);
mPostImage = (SquareImageView) view.findViewById(R.id.post_image);
bottomNavigationViewEx = (BottomNavigationViewEx) view.findViewById(R.id.bottomNavViewBar);
mBackArrow = (ImageView) view.findViewById(R.id.backArrow);
mBackLabel = (TextView) view.findViewById(R.id.tvBackLabel);
mCaption = (TextView) view.findViewById(R.id.image_caption);
mUsername = (TextView) view.findViewById(R.id.username);
mTimeStamp = (TextView) view.findViewById(R.id.image_time_posted);
mEllipses = (ImageView) view.findViewById(R.id.iv_ellipses);
mStars = (RatingBar) view.findViewById(R.id.ratingBar);
mStars.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RatingBar bar = (RatingBar) v;
Log.d(TAG,"VALUE IS : "+bar.getRating()+" **************************************************");
}
});
mStars.setRating(0);
mProfileImage = (ImageView) view.findViewById(R.id.profile_photo);
try {
mPhoto = getPhotoFromBundle();
UniversalImageLoader.setImage(mPhoto.getImage_path(), mPostImage, null, "");
} catch (NullPointerException e) {
Log.e(TAG, "onCreateView NullPointerException : " + e.getMessage());
}
setupBottomNavigationView();
setupFirebaseAuth();
getPhotoDetails();
setupWidgets();
return view;
}
private void getPhotoDetails(){
Log.d(TAG, "getPhotoDetails: retrieving photo details.");
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child(getString(R.string.dbname_user_account_settings))
.orderByChild(getString(R.string.field_user_id))
.equalTo(mPhoto.getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: ");
for ( DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "onDataChange: " +singleSnapshot.getValue().toString());
mUserAccountSettings = singleSnapshot.getValue(UserAccountSettings.class);
Log.d(TAG, "onDataChange: "+mUserAccountSettings.getUsername());
}
setupWidgets();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: query cancelled.");
}
});
}
private void setupWidgets(){
String timestampDiff = getTimeStampDifference();
if(!timestampDiff.equals("0")){
mTimeStamp.setText(timestampDiff + " DAYS AGO");
}else{
mTimeStamp.setText("TODAY");
}
UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
mUsername.setText(mUserAccountSettings.getUsername());
}
//get how many days ago of post
private String getTimeStampDifference() {
Log.d(TAG, "getTimeStampDifference : getting time difference");
String difference = "";
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy'T'HH:mm:ss'Z'", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Jakarta"));
Date timestamp;
Date today = c.getTime();
sdf.format(today);
final String photoTimestamp = mPhoto.getDate_created();
try {
timestamp = sdf.parse(photoTimestamp);
difference = String.valueOf(Math.round(((today.getTime() - timestamp.getTime()) / 1000 / 60 / 60 / 24)));
} catch (ParseException e) {
Log.e(TAG, "PARSE EXCEPTION : " + e.getMessage());
difference = "0";
}
return difference;
}
private int getActivityFromBundle() {
Log.d(TAG, "getActivityFromBundle arguments : " + getArguments());
Bundle bundle = this.getArguments();
if (bundle != null) {
return bundle.getInt(getString(R.string.activity_number));
} else {
return 0;
}
}
private Photo getPhotoFromBundle() {
Log.d(TAG, "getPhotoFromBundle arguments : " + getArguments());
Bundle bundle = this.getArguments();
if (bundle != null) {
return bundle.getParcelable(getString(R.string.photo));
} else {
return null;
}
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView() {
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(getActivity(), getActivity(), bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(mActivityNumber);
menuItem.setChecked(true);
}
/**
* ----------------------------------Firebase stuffs-----------------------------------------
*/
//setup the firebase auth obj
private void setupFirebaseAuth() {
Log.d(TAG, "setupFirebaseAuth : setting up firebase auth");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
//user is signed in
Log.d(TAG, "user is signed in" + user.getUid());
} else {
//user is signed out
Log.d(TAG, "onAuthStateChanged : signed out");
}
}
};
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
It is because the variable mUserAccountSettings is initialized in onDataChange() method which is a callback and is executed async. Before this it initialized your main thread is trying to access that in setupWidgets()
A possible fix would be to move the below code from setupWidgets() to onDataChange().
UniversalImageLoader.setImage(mUserAccountSettings.getProfile_photo(), mProfileImage, null, "");
NOTE: this is not intend to show you any best practice. This solution is just to show that all UI updates which depends on value from server, should happen ones you get the response from server.

GoogleFit Steps Count return zero after exiting the fragment's parent activity (signout)

I am working on GoogleFit Api for daily steps count. I am getting the correct result. But when i sign out the application (In this case, app exit the Googlefit fragment's parent activity)
After sign in again, i access the same fragment again, but Googlefit returns the stepsCount as zero and getting times out at result.await.
Here is my Code.
GoogleFitFragment.java
package com.example.mudasirrao.mvvm.Fragments.GoogleFitFragments;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mudasirrao.mvvm.R;
import com.example.mudasirrao.mvvm.ViewModel.GoogleFitViewModels.GoogleFitViewModel;
import com.example.mudasirrao.mvvm.databinding.FragmentGoogleFitBinding;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.ConfigApi;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.result.DataTypeResult;
public class GoogleFitFragment extends Fragment {
GoogleFitViewModel googleFitViewModel;
public GoogleFitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
FragmentGoogleFitBinding fragmentGoogleFitBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_google_fit, container, false);
View view = fragmentGoogleFitBinding.getRoot();
googleFitViewModel = new GoogleFitViewModel(getActivity(), fragmentGoogleFitBinding);
fragmentGoogleFitBinding.setGoogleFitFragmentViewModel(googleFitViewModel);
return view;
}
}
GoogleFitViewModel.java
package com.example.mudasirrao.mvvm.ViewModel.GoogleFitViewModels;
import android.content.Context;
import android.content.SharedPreferences;
import android.databinding.ObservableField;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.example.mudasirrao.mvvm.CallBacks.CallBackGoogleFitClient;
import com.example.mudasirrao.mvvm.DataManager.GoogleFitDataManager;
import com.example.mudasirrao.mvvm.databinding.FragmentGoogleFitBinding;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.fitness.ConfigApi;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.fitness.result.DailyTotalResult;
import java.util.concurrent.TimeUnit;
import static android.content.Context.MODE_PRIVATE;
public class GoogleFitViewModel {
private Context context;
private FragmentGoogleFitBinding fragmentGoogleFitBinding;
public final ObservableField<String> steps = new ObservableField<>();
public GoogleApiClient localGoogleApiClient;
String dailySteps;
public GoogleFitViewModel(Context context, final FragmentGoogleFitBinding fragmentGoogleFitBinding) {
this.context = context;
this.fragmentGoogleFitBinding = fragmentGoogleFitBinding;
SharedPreferences prefs = context.getSharedPreferences("dailySteps", MODE_PRIVATE);
dailySteps = prefs.getString("daily_steps", null);
if (dailySteps != null) {
steps.set(dailySteps);
GoogleFitDataManager.singletonObject(context).buildFitnessClient(new CallBackGoogleFitClient() {
#Override
public void onResponse(GoogleApiClient googleApiClient) {
localGoogleApiClient = googleApiClient;
if (googleApiClient != null) {
new VerifyDataTask().execute(localGoogleApiClient);
fragmentGoogleFitBinding.setGoalLayout.animate().alpha(0.2f).setDuration(1000);
enableDisableLayout(false);
fragmentGoogleFitBinding.previewImage.setVisibility(View.GONE);
fragmentGoogleFitBinding.saveButton.setText("Edit");
fragmentGoogleFitBinding.saveButton.setTag("disabled_edit");
fragmentGoogleFitBinding.goalProgressLayout.setVisibility(View.VISIBLE);
fragmentGoogleFitBinding.goalText.setText("Take " + steps.get() + " steps a day");
}
}
});
} else {
steps.set("0000");
fragmentGoogleFitBinding.setGoalLayout.animate().alpha(1.0f).setDuration(3000);
}
}
public void onClickStepsButton1(View view) {
steps.set("2000");
}
public void onClickStepsButton2(View view) {
steps.set("8000");
}
public void onClickStepsButton3(View view) {
steps.set("10000");
}
public void onClickStepsButton4(View view) {
steps.set("13000");
}
public void onClickSave(View view) {
if ((Integer.valueOf(steps.get()) > 0)) {
if (fragmentGoogleFitBinding.saveButton.getTag() == null) {
GoogleFitDataManager.singletonObject(context).buildFitnessClient(new CallBackGoogleFitClient() {
#Override
public void onResponse(GoogleApiClient googleApiClient) {
localGoogleApiClient = googleApiClient;
if (googleApiClient != null) {
new VerifyDataTask().execute(localGoogleApiClient);
fragmentGoogleFitBinding.setGoalLayout.animate().alpha(0.2f).setDuration(1000);
enableDisableLayout(false);
fragmentGoogleFitBinding.previewImage.setVisibility(View.GONE);
fragmentGoogleFitBinding.saveButton.setText("Edit");
fragmentGoogleFitBinding.saveButton.setTag("disabled_edit");
fragmentGoogleFitBinding.goalProgressLayout.setVisibility(View.VISIBLE);
}
}
});
} else {
if (fragmentGoogleFitBinding.saveButton.getTag().equals("disabled_edit")) {
fragmentGoogleFitBinding.setGoalLayout.animate().alpha(1.0f).setDuration(1000);
enableDisableLayout(true);
fragmentGoogleFitBinding.saveButton.setTag("enabled_edit");
fragmentGoogleFitBinding.saveButton.setText("Save");
} else if (fragmentGoogleFitBinding.saveButton.getTag().equals("enabled_edit")) {
new VerifyDataTask().execute(localGoogleApiClient);
fragmentGoogleFitBinding.setGoalLayout.animate().alpha(0.2f).setDuration(1000);
enableDisableLayout(false);
fragmentGoogleFitBinding.saveButton.setText("Edit");
fragmentGoogleFitBinding.saveButton.setTag("disabled_edit");
}
}
fragmentGoogleFitBinding.goalText.setText("Take " + steps.get() + " steps a day");
} else
Toast.makeText(context, "Please Select Steps", Toast.LENGTH_SHORT).show();
}
protected void renderStepsProgress(int stepsTaken) {
saveDailyStepsInSharedPref(steps.get());
int percentage = (int) (((double) stepsTaken / (double) Integer.valueOf(steps.get())) * 100);
if (percentage > 100) {
percentage = 100;
}
fragmentGoogleFitBinding.waveLoadingView.setCenterTitle(String.valueOf(percentage) + " %");
fragmentGoogleFitBinding.waveLoadingView.setProgressValue(percentage);
fragmentGoogleFitBinding.stepsTakenText.setText("You have taken " + String.valueOf(stepsTaken) + " steps today");
}
private void enableDisableLayout(Boolean visibility) {
View child;
for (int i = 0; i < fragmentGoogleFitBinding.stepButtonLayout1.getChildCount(); i++) {
child = fragmentGoogleFitBinding.stepButtonLayout1.getChildAt(i);
child.setEnabled(visibility);
}
for (int i = 0; i < fragmentGoogleFitBinding.stepButtonLayout2.getChildCount(); i++) {
child = fragmentGoogleFitBinding.stepButtonLayout2.getChildAt(i);
child.setEnabled(visibility);
}
}
private void saveDailyStepsInSharedPref(String dailySteps) {
SharedPreferences.Editor editor = context.getSharedPreferences("dailySteps", MODE_PRIVATE).edit();
editor.putString("daily_steps", dailySteps);
editor.apply();
}
private class VerifyDataTask extends AsyncTask<GoogleApiClient, Void, Integer> {
#Override
protected Integer doInBackground(GoogleApiClient... params) {
int total = 0;
PendingResult<DailyTotalResult> result = Fitness.HistoryApi.readDailyTotal(params[0], DataType.TYPE_STEP_COUNT_DELTA);
DailyTotalResult totalResult = result.await(30, TimeUnit.SECONDS);
if (totalResult.getStatus().isSuccess()) {
DataSet totalSet = totalResult.getTotal();
total = totalSet.isEmpty()
? 0
: totalSet.getDataPoints().get(0).getValue(Field.FIELD_STEPS).asInt();
} else {
Log.d("steps_count_error", "There was a problem getting the step count!!");
}
return total;
}
protected void onPostExecute(Integer result) {
renderStepsProgress(result);
}
}
}
GoogleFitDataManager.java
package com.example.mudasirrao.mvvm.DataManager;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.example.mudasirrao.mvvm.CallBacks.CallBackGoogleFitClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessStatusCodes;
import com.google.android.gms.fitness.data.DataType;
import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;
public class GoogleFitDataManager {
private static GoogleFitDataManager googleFitDataManager;
private GoogleApiClient googleApiClient = null;
private Context context;
public GoogleFitDataManager(Context context) {
this.context = context;
}
public static GoogleFitDataManager singletonObject(Context context) {
if (googleFitDataManager == null) {
googleFitDataManager = new GoogleFitDataManager(context);
}
return googleFitDataManager;
}
public void buildFitnessClient(final CallBackGoogleFitClient callBackGoogleFitClient) {
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(Fitness.HISTORY_API)
.addApi(Fitness.RECORDING_API)
.addApi(Fitness.CONFIG_API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnected(#Nullable Bundle bundle) {
subscribeGoogleFit(googleApiClient);
callBackGoogleFitClient.onResponse(googleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_NETWORK_LOST) {
Toast.makeText(context, "Connection lost. Cause: Network Lost.", Toast.LENGTH_SHORT).show();
} else if (i == GoogleApiClient.ConnectionCallbacks.CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(context, "Connection lost. Reason: Service Disconnected", Toast.LENGTH_SHORT).show();
}
}
}
)
.enableAutoManage((FragmentActivity) context, 0, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i("TAG", "Google Play services connection failed. Cause: " + result.toString());
Toast.makeText(context, "Exception while connecting to Google Play services: " + result.getErrorMessage(), Toast.LENGTH_SHORT).show();
}
})
.build();
} else {
subscribeGoogleFit(googleApiClient);
callBackGoogleFitClient.onResponse(googleApiClient);
}
}
public void subscribeGoogleFit(GoogleApiClient client) {
Fitness.RecordingApi.subscribe(client, DataType.TYPE_STEP_COUNT_DELTA)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (status.isSuccess()) {
if (status.getStatusCode() == FitnessStatusCodes.SUCCESS_ALREADY_SUBSCRIBED) {
Log.i(TAG, "Existing subscription for activity detected.");
} else {
Log.i(TAG, "Successfully subscribed!");
}
} else {
Log.i(TAG, "There was a problem subscribing.");
}
}
});
}
}
What I was doing that I was creating the static object of the class in which I was making the googlefit client. In this case, when I exit the Activity, the object was not destroying and googlefit client was getting disconnected due to the enableAutoManage in onDestroy of the fragment. And as per my checks, I was not connecting to the googleFit client again.
I removed the object as static and now I stick the API client class object with the life cycle of the activity in which my fragment resides. Also I removed enableAutoManage and now connecting and disconnecting the API client by myself.

Why do I get an "unreachable code" and "variable not initialized" compilation error?

Hi I am New to java and trying to develop an already existing Anti-ragging application to support newer api like lollipop from gingerbread. I have decompiled the apk and extracted the source code and built it in Gradle system.
Although the source code is correct,I am getting 3 errors in java code...not been able to figure out from a week.
The app contains 4 screens. The main screen is with a send button to send message, the second settings screen with two buttons to set message which we want to send and set contacts whom we want to send the message... the other two screens are the custom dialog layouts of the Set Meaasge & contact.
No errors in this main Java file just giving it for a reference
MainActivity.java:
package com.eminem.sharath.antiragging;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
String[] arrr1;
private ImageButton ib1;
private double latitude;
private LocationManager lm;
private double longitude;
private SharedPreferences sp;
private SharedPreferences sp1;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.mipmap.ic_launcher);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayUseLogoEnabled(true);
this.ib1 = (ImageButton)findViewById(R.id.imageButton1);
this.lm = (LocationManager)getSystemService(LOCATION_SERVICE);
this.ib1.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
MainActivity.this.sp = MainActivity.this.getSharedPreferences("demo", 1);
final String str1 = MainActivity.this.sp.getString("aaa", "");
MainActivity.this.sp1 = MainActivity.this.getSharedPreferences("sdat", 1);
String str2 = MainActivity.this.sp1.getString("snum", "");
MainActivity.this.arrr1 = str2.split(",");
Toast.makeText(MainActivity.this.getApplicationContext(), str2 + str1, Toast.LENGTH_SHORT).show();
System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLL" + str2 + str1);
MainActivity.this.lm.requestLocationUpdates("gps", 1000L, 5.0F, new LocationListener() {
public void onLocationChanged(Location paramAnonymous2Location) {
Location localLocation = MainActivity.this.lm.getLastKnownLocation("gps");
MainActivity.this.latitude = localLocation.getLatitude();
MainActivity.this.longitude = localLocation.getLongitude();
Toast.makeText(MainActivity.this.getApplicationContext(), "Latitude:" + MainActivity.this.latitude + "\n" + "Longitude:" + MainActivity.this.longitude, Toast.LENGTH_SHORT).show();
String str = "http://maps.google.com/maps?=" + MainActivity.this.latitude + "," + MainActivity.this.longitude;
for (int i = 0; ; i++) {
if (i >= MainActivity.this.arrr1.length) {
return;
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + MainActivity.this.arrr1);
SmsManager.getDefault().sendTextMessage(MainActivity.this.arrr1[i], null, str1 + " Come at this location" + str, null, null);
}
}
public void onProviderDisabled(String paramAnonymous2String) {
}
public void onProviderEnabled(String paramAnonymous2String) {
}
public void onStatusChanged(String paramAnonymous2String, int paramAnonymous2Int, Bundle paramAnonymous2Bundle) {
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
startActivity(new Intent(getApplicationContext(), Settingss.class));
return super.onOptionsItemSelected(item);
}
}
The three errors are in this settings file...i have commented the error name beside the error for reference.
Settings.java:
package com.eminem.sharath.antiragging;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.MultiAutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView.CommaTokenizer;
import android.widget.Toast;
import java.io.PrintStream;
import java.util.ArrayList;
public class Settingss extends AppCompatActivity
{
private ArrayList<String> alist = new ArrayList();
private Button b1;
private Button b2;
SharedPreferences.Editor ed;
private String setnum = "";
SharedPreferences sp;
protected void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.contact);
this.b1 = ((Button)findViewById(R.id.button1));
this.b2 = ((Button)findViewById(R.id.button2));
this.b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Settingss.this.showDialog(1);
}
});
this.b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
Settingss.this.showDialog(2);
}
});
}
protected Dialog onCreateDialog(int paramInt) {
if (paramInt == 1) {
final Dialog localDialog1 = new Dialog(this);
localDialog1.setContentView(R.layout.tosetmessage);
localDialog1.setTitle("Set Message");
final EditText localEditText = (EditText)findViewById(R.id.editText1);
Button localButton1 = (Button)findViewById(R.id.button1);
Button localbutton2 = ((Button) findViewById(R.id.button2));
localbutton2.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView) {
Settingss.this.sp = Settingss.this.getSharedPreferences("demo", 2);
Settingss.this.ed = Settingss.this.sp.edit();
Settingss.this.ed.putString("aaa", localEditText.getText().toString());
Settingss.this.ed.commit();
localDialog1.dismiss();
}
});
localButton1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
localDialog1.dismiss();
}
});
localDialog1.show();
}
while(true)
{
return super.onCreateDialog(paramInt);
/*Error: unreachale statement*/ if (paramInt == 2)
{
final Dialog localDialog2 = new Dialog(this);
localDialog2.setContentView(R.layout.multiautotext);
localDialog2.setTitle("Set Contacts");
final MultiAutoCompleteTextView localMultiAutoCompleteTextView = (MultiAutoCompleteTextView)localDialog2.findViewById(R.id.multiAutoCompleteTextView1);
Button localButton2 = (Button)localDialog2.findViewById(R.id.button1);
Button localButton3 = (Button)localDialog2.findViewById(R.id.button2);
Cursor localCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, "display_name ASC");
if (localCursor.moveToFirst())
{
do
{
String str1 = localCursor.getString(localCursor.getColumnIndex("display_name"));
String str2 = localCursor.getString(localCursor.getColumnIndex("data1"));
String str3 = str1 + "%" + str2;
this.alist.add(str3);
} while (localCursor.moveToNext());
ArrayAdapter localArrayAdapter = new ArrayAdapter(this, R.layout.simple_list_item, this.alist);
localMultiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
localMultiAutoCompleteTextView.setAdapter(localArrayAdapter);
}
localButton2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
String[] arrayOfString = localMultiAutoCompleteTextView.getText().toString().split(",");
int i = 0;
if (i >= arrayOfString.length)
{
System.out.println("************************" + Settingss.this.setnum);
Toast.makeText(Settingss.this.getApplicationContext(), Settingss.this.setnum, Toast.LENGTH_SHORT).show();
Settingss.this.sp = Settingss.this.getSharedPreferences("sdat", 2);
Settingss.this.ed = Settingss.this.sp.edit();
Settingss.this.ed.putString("snum", Settingss.this.setnum);
Settingss.this.ed.commit();
Settingss.this.setnum = "";
Settingss.this.finish();
return;
}
String str2;
if (arrayOfString[i].contains("%"))
str2 = arrayOfString[i].split("%")[1];
String str1;
for (Settingss.this.setnum = (Settingss.this.setnum + /*Error: Variable Str2 might not have been initialized*/ str2 + ",");; Settingss.this.setnum = (Settingss.this.setnum + str1 + ","))
{
i++;
break;
/*Error: unreachale statement*/ str1 = arrayOfString[i];
}
}
});
localButton3.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
localDialog2.dismiss();
}
});
localDialog2.show();
}
}
}
}
Please help me debug the application.
I have no intention to take any credits for the application because as I haven't developed it...just want to play with the user interface and give it a taste of new api.
The return statement will cause the onCreateDialog method to return and any subsequent lines will not be executed. That's why you get the unreachable code error message. Similarly, the break statement will cause the for loop to end. Any subsequent lines will not be executed.
Finally, you get a /*Error: Variable Str2 might not have been initialized*/ error because all local variables must be initialized before they can be used for the first time.
For /*Error: Variable Str2 might not have been initialized*/:
Change String str2; to String str2 = "";
As for the other two errors, you have a return; and break; before those lines.
Any statements after a unconditional return and break will be unreachable, i.e. there is no way that the code there (subsequent lines) will execute.

Value of EditText not appearing in my logs

I an new to Android. I have the following code for a Twitter Client search:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
if (searchResults == null)
{
Log.w(LogConstants.LOG, "searchResults is null");
}
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
The issue is, I have tried to log the results of the EditText, however I never see that in the logs. What is going on here? I can't work out why I'm never seeing "Text value is " + queryText in the logs.
The problem is you initialize the String value queryText in the event of the screen being created (onCreate()) and not when you actually type in values (after screen creation & dynamic activity on the screen).
This is why the following would work
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if (queryText.equals("")) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
Change
Log.i(LogConstants.LOG, "Text value is " + queryText);
to
Log.i(LogConstants.LOG, "Text value is " + queryEditText.getText().toString());
Move
queryText = (queryEditText.getText().toString());
inside the onClick
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
queryText = (queryEditText.getText().toString());
Log.i(LogConstants.LOG, "Text value is " + queryText);
if ("".equals(queryText)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});

Categories