Android ZXING barcodescan put result value in string - java

I am trying to get the result value in a string after there has been scanned.
but it wont work.
I already figured out how to put it in a toast(maketext) that works but a string I cant figure it out.
here's the code please help me.
cpackage com.example.stage.absa;
import android.Manifest;
import android.content.ClipData;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.zxing.Result;
import java.io.IOException;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import android.net.Uri;
import java.net.URL;
public class MainActivity extends AbsRuntimePermission {
String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
scannerView.setResultHandler(new ZxingScannerResultHandler());
setContentView(scannerView);
scannerView.startCamera();
}
class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}

remove the String declaration and instead move it as a class member
public void handleResult(Result result) {
//String resultCode = result.getText();
resultCode = result.getText();
like:
myClass extends Activity... {
String resultCode;
}
now you can assign the result code in the hadnleResult callback and use it in the same activity whenever you need it!
Edit:
you have an inner class, i would get rid of that and directly implement the ZXingScannerView.ResultHandler interface:
example:
public class MainActivity extends AbsRuntimePermission implements ZXingScannerView.ResultHandler{
private String resultCode;
private Button getBtn;
private TextView result;
private OkHttpClient client;
boolean doubleTap = false;
private ZXingScannerView scannerView;
private static final int REQUEST_PERMISSION = 10;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
getBtn = (Button) findViewById(R.id.getBtn);
getBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getWebService();
}
});
client = new OkHttpClient();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
requestAppPermissions(new String[]{
Manifest.permission.CAMERA},
R.string.msg, REQUEST_PERMISSION);
}
#Override
public void onBackPressed() {
if (doubleTap) {
super.onBackPressed();
} else {
Toast.makeText(this, "Druk Terug opnieuw om de app te sluiten", Toast.LENGTH_SHORT).show();
doubleTap = true;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
doubleTap = false;
}
}, 500);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
public void browser1(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.suppliance.nl/"));
startActivity(browserIntent);
}
public void scanCode(View view) {
scannerView = new ZXingScannerView(this);
//scannerView.setResultHandler(new ZxingScannerResultHandler());
scannerView.setResultHandler(this);
setContentView(scannerView);
scannerView.startCamera();
}
//class ZxingScannerResultHandler implements ZXingScannerView.ResultHandler {
#Override
public void handleResult(Result result) {
// String resultCode = result.getText();
// Toast.makeText(MainActivity.this, resultCode, Toast.LENGTH_SHORT).show();
resultCode = result.getText();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
scannerView.stopCamera();
}
//}
private void getWebService() {
Uri.Builder builder = new Uri.Builder();
builder.scheme("http")
.appendPath(getString(R.string.ipadres))
.appendPath(getString(R.string.poort))
.authority("barcode/")
.appendPath(getString(R.id.))
String URL = builder.build().toString();
final Request request = new Request.Builder().url("http://192.168.17.12:9083/barcode/8712345501006").build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
result.setText("Mislukt");
}
});
}
#Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
result.setText(response.body().string());
} catch (IOException ioe) {
result.setText("Error tijdens verkrijgen body");
}
}
});
}
});
}
#Override
public void onPermissionsGranted(int requestCode) {
//Do anything when permisson granted
Toast.makeText(getApplicationContext(), "Toegang geaccepteerd", Toast.LENGTH_LONG).show();
}
}

I will go with this or something similar, depending on how you are handling the scanner view
public class MainActivity extends AppCompatActivity
implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private String resultCode;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
resultCode = rawResult.getText();
//now use resultCode
}
}

Related

Use CustomAdapter and OnItenClickListener. Listener is not responding

Here is my code.
I try to add OnItenClickListener to "lastCommand" listView but it is not responde. Any errors at compile.
package pl.globoox.sprawdzsprzedawce;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import pl.globoox.sprawdzsprzedawce.Utils.LastCommentHome;
import pl.globoox.sprawdzsprzedawce.Utils.QueryCheck;
import static pl.globoox.sprawdzsprzedawce.R.id.buttonCheckButton;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ListView lastComments;
LoginButton loginButton;
CallbackManager callbackManager;
ArrayList<String> comments_userList = new ArrayList();
ArrayList<String> comments_olxUserList = new ArrayList();
ArrayList<String> comments_dateList = new ArrayList();
ArrayList<String> comments_messageList = new ArrayList();
ArrayList<String> comments_statusList = new ArrayList();
ImageView imageViewFBUser;
TextView textViewFBName;
TextView textViewFBEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
initializeControls();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
loginWithFb();
// MENU DRAWER
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View headerView = navigationView.getHeaderView(0);
textViewFBName = headerView.findViewById(R.id.textViewFBName);
textViewFBEmail = headerView.findViewById(R.id.textViewFBEmail);
imageViewFBUser = headerView.findViewById(R.id.imageViewFBUser);
imageViewFBUser.setVisibility(View.INVISIBLE);
textViewFBName.setText("");
textViewFBEmail.setText("");
// MAIN CONTENT APP
final SearchView editTextOfferLink = (SearchView) findViewById(R.id.editTextOfferLink);
final Button buttonCheck = (Button) findViewById(buttonCheckButton);
lastComments = (ListView) findViewById(R.id.listViewLastComments);
buttonCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String offerLink = editTextOfferLink.getQuery().toString();
boolean error = false;
// CHECK FORM EMPTY
if (offerLink.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.formEmpty).setNegativeButton(R.string.tryAgain, null).create().show();
error = true;
return;
}
if (error == false) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
String userID = jsonResponse.getString("userID");
// CANT CONNECT TO DATABASE
if (errorCode == 1) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.cantConnectToDatabase).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER NOT FOUND
else if (errorCode == 2) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), AddNewUserActivity.class);
if (isBank == true) {
i.putExtra("isBank", "true");
} else {
i.putExtra("isBank", "false");
}
String userName = jsonResponse.getString("userName");
String registerDate = jsonResponse.getString("registerDate");
i.putExtra("userID", userID);
i.putExtra("userName", userName);
i.putExtra("registerDate", registerDate);
finish();
startActivity(i);
}
// EMPTY OFFER VARIABLE
else if (errorCode == 3) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.omptyOfferVariable).setNegativeButton(R.string.tryAgain, null).create().show();
}
// BAD LINK
else if (errorCode == 4) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.badOfferLink).setNegativeButton(R.string.tryAgain, null).create().show();
}
// USER FOUND!
else if (errorCode == 5) {
Boolean isBank = jsonResponse.getBoolean("isBank");
Intent i;
i = new Intent(getApplicationContext(), UserAreaActivity.class);
i.putExtra("userID", userID);
i.putExtra("isBank", isBank.toString());
finish();
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
QueryCheck offerQueryRequest = new QueryCheck(offerLink, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(offerQueryRequest);
}
}
});
// LAST COMMENTS SHOW
Response.Listener<String> responseListenerLastComments = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
int errorCode = jsonResponse.getInt("errorCode");
int count = jsonResponse.getInt("count");
Log.d("Tag", String.valueOf(errorCode));
JSONArray commentsArray = jsonResponse.getJSONArray("comments");
Log.d("TAG", String.valueOf(commentsArray));
for (int i = 0; i < count; i++) {
JSONObject jsonObject = commentsArray.getJSONObject(i);
comments_userList.add(jsonObject.getString("user"));
comments_olxUserList.add(jsonObject.getString("olxUser"));
comments_dateList.add(jsonObject.getString("date"));
comments_messageList.add(jsonObject.getString("message"));
comments_statusList.add(jsonObject.getString("status"));
}
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
lastComments.setAdapter(customAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LastCommentHome lastCommentHome = new LastCommentHome("3", responseListenerLastComments);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(lastCommentHome);
}
private void loginWithFb() {
// LOGIN MANAGER FACEBOOK
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest.newMeRequest(
loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject me, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
String email = me.optString("email");
String name = me.optString("name");
String picture = me.optString("picture");
imageViewFBUser.setVisibility(View.VISIBLE);
imageViewFBUser.setImageURI(Uri.parse(picture));
textViewFBName.setText(name);
textViewFBEmail.setText(email);
}
}
}).executeAsync();
}
#Override
public void onCancel() {
textViewFBName.setText("Login canceled!");
}
#Override
public void onError(FacebookException error) {
textViewFBName.setText("Login error: " + error.getMessage());
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
// FACEBOOK INITALZIZE LOGIN
private void initializeControls() {
callbackManager = CallbackManager.Factory.create();
loginButton = findViewById(R.id.login_button);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_search) {
// Handle the camera action
} else if (id == R.id.nav_best) {
} else if (id == R.id.nav_worst) {
} else if (id == R.id.nav_comments) {
} else if (id == R.id.nav_policy) {
} else if (id == R.id.nav_rules) {
} else if (id == R.id.nav_about) {
} else if (id == R.id.nav_contact) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class CustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
lastComments.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Log.d("asdasdxxxxx", String.valueOf(position));
}});
return convertView;
}
}
}
You can create your own interface :
private interface OnListItemClickListener
{
void onListItemClicked(View view, int position);
}
Then use it in your adapter class this way:
class CustomAdapter extends BaseAdapter {
//create an instance
private OnListItemClickListener onListItemClickListener;
//define the object setter
void setOnListItemClickListener(OnListItemClickListener listener)
{
this.onListItemClickListener=listener;}
#Override
public int getCount() {
return comments_dateList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public boolean isEnabled(int position) {
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.customlayout_lastcomment_homepage, null);
TextView textViewUser = (TextView) convertView.findViewById(R.id.textViewUser);
TextView textViewDate = (TextView) convertView.findViewById(R.id.textViewDate);
TextView textViewMessage = (TextView) convertView.findViewById(R.id.textViewMessage);
textViewUser.setText(comments_userList.get(position));
textViewDate.setText(comments_dateList.get(position));
textViewMessage.setText(comments_messageList.get(position));
//Then here trigger
convertView.setOnClickListener(new View.OnClickListener()
{
#override
void onClick(View v)
{
onListItemClickListener.onListItemClicked(v,position);
//you may be asked to set position as final
}
});
return convertView;
}
}
Then in your onCreate method where you attached the adapter, set the listener to your adapter:
MainActivity.CustomAdapter customAdapter = new MainActivity.CustomAdapter();
customAdapter.setOnListItemClickListener(new OnListItemClickListener()
{
#override
void onListItemClicked(View view,int position)
{
//then here place your desired action
}
});
lastComments.setAdapter(customAdapter);
I hope this may be helpful. You can still ask for clarifications in comment

Swipe to refresh webview fragment doesnt load url

I have a webview fragment in my MainActivity. I am trying to add Swipetoview inside it. But when I load the fragment it doesn't load the url.
My fragment:
// Inflate the layout for this fragment
View vDriver=inflater.inflate(R.layout.fragment_drivers, container, false);
mWebView = vDriver.findViewById(R.id.drivers_webview);
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
// Enable Javascript
//WebSettings webSettings = mWebView.getSettings();
//webSettings.setJavaScriptEnabled(true);
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
swipeLayout = vDriver.findViewById(R.id.fragment_drivers);
swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mWebView.reload();
new Handler().postDelayed(new Runnable() {
#Override public void run() {
swipeLayout.setRefreshing(false);
}
}, 5000);
}
});
return vDriver;
My fragment layout:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_drivers"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Drivers">
<WebView
android:id="#+id/drivers_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
I tried different things and this is the last code I tried. What am I doing wrong?
Thanks for your time in advance.
EDIT: MainActivity
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
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.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.squareup.picasso.Picasso;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, HomeFragment.OnFragmentNavListener,Drivers.OnDriverNavigationListener {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private GoogleApiClient mGoogleApiClient;
private static final int RC_SIGN_IN = 0 ;
private SignInButton btn_signin;
private TextView nameText;
private TextView emailText;
private ImageView imgProfilePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
HomeFragment fragment = new HomeFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View navHeader1 = navigationView.getHeaderView(0);
btn_signin = navHeader1.findViewById(R.id.signin_btn);
View navHeader3 = navigationView.getHeaderView(0);
nameText = navHeader3.findViewById(R.id.name);
View navHeader4 = navigationView.getHeaderView(0);
emailText = navHeader4.findViewById(R.id.email);
View navHeader5 = navigationView.getHeaderView(0);
imgProfilePic = navHeader5.findViewById(R.id.imgProfilePic);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
})
.addApi(Auth.GOOGLE_SIGN_IN_API, gso).build();
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null){
btn_signin.setVisibility(View.GONE);
if(user.getDisplayName() != null) {
nameText.setText(user.getDisplayName());
nameText.setVisibility(View.VISIBLE);
}
emailText.setText(user.getEmail());
emailText.setVisibility(View.VISIBLE);
imgProfilePic.setVisibility(View.VISIBLE);
Picasso.get().load(user.getPhotoUrl())
.into(imgProfilePic);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(false);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(true);
}
else {
nameText.setVisibility(View.GONE);
emailText.setVisibility(View.GONE);
btn_signin.setVisibility(View.VISIBLE);
NavigationView navigationView2 = findViewById(R.id.nav_view);
Menu menu = navigationView2.getMenu();
MenuItem target = menu.findItem(R.id.nav_send);
target.setVisible(true);
MenuItem target2 = menu.findItem(R.id.nav_send2);
target2.setVisible(false);
imgProfilePic.setVisibility(View.GONE);
}
}
};
btn_signin.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
signIn();
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
private void signIn () {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
// deneme
}
}
}
#Override
public void onStop() {
super.onStop();
if(mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Authentication failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(final MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
signIn();
} else if (id == R.id.nav_send2) {
FirebaseAuth.getInstance().signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "Çıkış yaptınız.", Toast.LENGTH_SHORT).show();
}
});
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentNav(int position) {
Fragment navFragment = null;
switch (position) {
case 0:
navFragment = new HomeFragment();
break;
case 1:
navFragment = new Drivers();
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.fragment_container, navFragment)
.addToBackStack(null)
.commit();
}
#Override
public void onDriverNavigation(int asd) {
}
}
HomeFragment.java
package com.ahmetbarpa.grandprix;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class HomeFragment extends Fragment {
private OnFragmentNavListener mListener;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v1 =inflater.inflate(R.layout.fragment_home, container, false);
Button profile= v1.findViewById(R.id.button1);
profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
onButtonSelected(1);
}
});
Button education= v1.findViewById(R.id.button2);
education.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Takımlar ve arabalar",Toast.LENGTH_SHORT).show();
}
});
Button health= v1.findViewById(R.id.button3);
health.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Pistler",Toast.LENGTH_SHORT).show();
}
});
Button goals= v1.findViewById(R.id.button4);
goals.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Sıralama",Toast.LENGTH_SHORT).show();
}
});
Button finance= v1.findViewById(R.id.button5);
finance.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"Grand Prix Tarihi",Toast.LENGTH_SHORT).show();
}
});
Button comfort= v1.findViewById(R.id.button6);
comfort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v1) {
Toast.makeText(getContext(),"GP kart oyunu",Toast.LENGTH_SHORT).show();
}
});
return v1;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonSelected(int position) {
if (mListener != null) {
mListener.onFragmentNav(position);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentNavListener) {
mListener = (OnFragmentNavListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentNav");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentNavListener {
void onFragmentNav(int position);
}
}
Instead of reload()
mWebView.loadUrl("https://ahmetbarpa-grand-prix.firebaseapp.com/drivers.html");
Try it..
If this is not the way you want, the second method is:
make a new class as:
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
then, Instead of this:
mWebView.setWebViewClient(new WebViewClient());
write this:
mWebView.setWebViewClient(new MyBrowser());
Hopefully your problem will be solved

Set UserImage and Username in nav header from Firebase

I'm following this Tutorial to create blog and I successfully Created the blog. In give Tutorial, he has used Empty Activity but I used Navigation drawer Activity.
So now I would like to put the User image and User name in nav header if he is signed in if not use the default image and name from drawable folder.
My Blog Recycle Adapter is
package com.nepalpolice.cdp;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.android.volley.VolleyLog.TAG;
import static com.nepalpolice.cdp.webfaq.isNetworkStatusAvialable;
public class BlogRecyclerAdapter extends RecyclerView.Adapter<BlogRecyclerAdapter.ViewHolder> {
public List<BlogPost> blog_list;
public Context context;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private PopupWindow popWindow;
public BlogRecyclerAdapter(List<BlogPost> blog_list){
this.blog_list = blog_list;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.blog_list_item, parent, false);
context = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
firebaseAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.setIsRecyclable(false);
final String blogPostId = blog_list.get(position).BlogPostId;
final String currentUserId = firebaseAuth.getCurrentUser().getUid();
String desc_data = blog_list.get(position).getDesc();
holder.setDescText(desc_data);
String image_url = blog_list.get(position).getImage_url();
String thumbUri = blog_list.get(position).getImage_thumb();
holder.setBlogImage(image_url, thumbUri);
String user_id = blog_list.get(position).getUser_id();
//User Data will be retrieved here...
firebaseFirestore.collection("Users").document(user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful()){
String userName = task.getResult().getString("name");
String userImage = task.getResult().getString("image");
holder.setUserData(userName, userImage);
} else {
//Firebase Exception
}
}
});
try {
long millisecond = blog_list.get(position).getTimestamp().getTime();
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
holder.setTime(dateString);
} catch (Exception e) {
Toast.makeText(context, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
//Get Likes Count
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").addSnapshotListener(((Main2Activity) context),new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (e!=null) {
Log.w(TAG, "listening failed",e);
return;
}
if(!documentSnapshots.isEmpty()){
int count = documentSnapshots.size();
holder.updateLikesCount(count);
} else {
holder.updateLikesCount(0);
}
}
});
if (InternetStatus.getInstance(holder.blogLikeBtn.getContext()).isOnline()) {
//Get Likes
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).addSnapshotListener(((Main2Activity) context), new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "listening failed", e);
return;
}
if (documentSnapshot.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_accent));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_accent));
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
holder.blogLikeBtn.setImageDrawable(context.getDrawable(R.mipmap.action_like_gray));
} else {
holder.blogLikeBtn.setImageDrawable(context.getResources().getDrawable(R.mipmap.action_like_gray));
}
}
}
});
//Likes Feature
holder.blogLikeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if(!task.getResult().exists()){
Map<String, Object> likesMap = new HashMap<>();
likesMap.put("timestamp", FieldValue.serverTimestamp());
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).set(likesMap);
} else {
firebaseFirestore.collection("Posts/" + blogPostId + "/Likes").document(currentUserId).delete();
}
}
});
}
});
}
else{
Toast.makeText(context, "Check Internet", Toast.LENGTH_SHORT).show();
}
holder.blogCommentBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent commentIntent = new Intent(context, CommentsActivity.class);
context.startActivity(commentIntent);
}
});
}
#Override
public int getItemCount() {
return blog_list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private TextView descView;
private ImageView blogImageView;
private TextView blogDate;
private TextView blogUserName;
private CircleImageView blogUserImage;
private ImageView blogLikeBtn;
private TextView blogLikeCount;
private ImageView blogCommentBtn;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
blogLikeBtn = mView.findViewById(R.id.blog_like_btn);
blogCommentBtn = mView.findViewById(R.id.blog_comment_icon);
}
public void setDescText(String descText){
descView = mView.findViewById(R.id.blog_desc);
descView.setText(descText);
}
public void setBlogImage(String downloadUri, String thumbUri){
blogImageView = mView.findViewById(R.id.blog_image);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.image_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(requestOptions).load(downloadUri).thumbnail(
Glide.with(context).load(thumbUri)
).into(blogImageView);
}
}
public void setTime(String date) {
blogDate = mView.findViewById(R.id.blog_date);
blogDate.setText(date);
}
public void setUserData(String name, String image) {
blogUserImage = mView.findViewById(R.id.blog_user_image);
blogUserName = mView.findViewById(R.id.blog_user_name);
blogUserName.setText(name);
RequestOptions placeholderOption = new RequestOptions();
placeholderOption.placeholder(R.drawable.profile_placeholder);
if (!((Activity) context).isFinishing()) {
Glide.with(context).applyDefaultRequestOptions(placeholderOption).load(image).into(blogUserImage);
}
}
public void updateLikesCount(int count){
blogLikeCount = mView.findViewById(R.id.blog_like_count);
blogLikeCount.setText(count + " Likes");
}
}
}
and my Mainactivity is
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
final Context context = this;
private boolean exit = false;
Dialog dialog;
private Menu mymenu;
private TextView blogUserName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Fragment fragment = new main();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
//Create Dialog
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mymenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ImageView iv = (ImageView)inflater.inflate(R.layout.iv_refresh, null);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate_refresh);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
item.setActionView(iv);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
new UpdateTask(this).execute();
}
return true;
}
return super.onOptionsItemSelected(item);
}
public void resetUpdating()
{
// Get our refresh item from the menu
MenuItem m = mymenu.findItem(R.id.action_refresh);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if(m.getActionView()!=null)
{
// Remove the animation.
m.getActionView().clearAnimation();
m.setActionView(null);
}
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.store) {
String url = "https://play.google.com/store/apps/developer?id=Sagar%20Rawal&hl=en";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else if (id == R.id.contact) {
Intent activity_about = new Intent(this, profile.class);
startActivity(activity_about);
} else if (id == R.id.weather) {
Intent activity_weather = new Intent(this, com.nepalpolice.cdp.weather.MainActivity.class);
startActivity(activity_weather);
}
else if (id == R.id.resistor) {
Intent activity_weather = new Intent(this, com.nepalpolice.cdp.resistor.MainActivity.class);
startActivity(activity_weather);
}
else if (id == R.id.result) {
result fragment = new result();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_frame, fragment, "Main");
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
else if (id == R.id.pacman) {
Intent activity_about = new Intent(this, pacman.class);
startActivity(activity_about);
}
else if (id == R.id.tetris) {
Intent activity_about = new Intent(this, MenuActivity.class);
startActivity(activity_about);
}
else if (id == R.id.retro) {
Intent intent500 = new Intent(this, com.nepalpolice.cdp.brickgame.GameActivity.class);
startActivity(intent500);
}
else if (id == R.id.hangman) {
Intent activity_about = new Intent(this, GameActivity.class);
startActivity(activity_about);
}
else if (id == R.id.tictac) {
Intent activity_about = new Intent(this, MainMenuScreen.class);
startActivity(activity_about);
}
else if (id == R.id.home) {
main fragment = new main();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_frame, fragment, "Main");
fragmentTransaction.commit();
fragmentTransaction.addToBackStack(null);
}
else if (id == R.id.email) {
Intent activity_about = new Intent(this, Sendemail.class);
startActivity(activity_about);
} else if (id == R.id.call) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+9779868336847"));
startActivity(intent);
} else if (id == R.id.share) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,
"Hey check out this awesome app at: https://play.google.com/store/apps/details?id=com.nepalpolice.cdp");
sendIntent.setType("text/plain");
startActivity(sendIntent);
} else if (id == R.id.rate) {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=com.nepalpolice.mnemonics&hl=en" + getPackageName())));
}
catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
(Uri.parse("https://play.google.com/store/apps/details?id=com.faraksoch.sagar.eroutine&hl=en"))));
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (exit)
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// MainActivity.super.onBackPressed();
finish();
moveTaskToBack(true);
}
}).create().show();
else {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
if (getSupportFragmentManager().getBackStackEntryCount() ==1) {
finish();
}
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 800);
}
}
}
I have no clue if it is possible or not but if it is please help. I have followed several post but none of it helped.
My Firebase Structure is

MainActivity has leaked ServiceConnection

This is my MainActivity.class. I am trying to make a music player app for Android. This player will run in the background. It plays a song but when I press the back button it shows the following errors on line number 105 and 118.
import com.example.shadowman.audio_player_two.MusicService.MusicBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.MediaController.MediaPlayerControl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import static android.content.Context.BIND_AUTO_CREATE;
public class MainActivity extends Activity implements MediaPlayerControl {
//song list variables
private ArrayList<Song> songList;
private ListView songView;
//service
private MusicService musicSrv;
private Intent playIntent;
//binding
private boolean musicBound=false;
//controller
private MusicController controller;
//activity and playback pause flags
private boolean paused=false, playbackPaused=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve list view
songView = (ListView)findViewById(R.id.song_list);
//instantiate list
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
//create and set adapter
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
//setup controller
setController();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//start and bind the service when the activity starts
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
//user song select
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//menu item selected
switch (item.getItemId()) {
case R.id.action_shuffle:
musicSrv.setShuffle();
break;
case R.id.action_end:
stopService(playIntent);
musicSrv=null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
//method to retrieve song info from device
public void getSongList(){
//query external audio
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//iterate over results if valid
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public void start() {
musicSrv.go();
}
//set the controller up
private void setController(){
controller = new MusicController(this);
//set previous and next button listeners
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
//set and show
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
protected void onPause(){
super.onPause();
paused=true;
}
#Override
protected void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
protected void onStop() {
if(controller !=null) {
controller.hide();
controller=null;
}
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopService(playIntent);
musicSrv=null;
}
}
Here is the error:
Please help me to understand & solve this error
You need to unbind service:
#Override
protected void onStop() {
// your onStop code
if(musicConnection != null) {
unbindService(musicConnection);
}
super.onStop();
}

Saving state while rotation

I Have an app in which the main activity shows a question and has true button false button and cheat button
When user press the correct option, listener will Toast Correct.. and otherwise listener will Toast Incorrect
Now when we press the cheat button new activity is launched and has a textview "Are you sure you want to cheat?", another textview which is blank and a show answer button..
When user presses the show answer button , the blank text view is set to the answer of the question (as asked in the main activity)
And when the user goes back the true and false button onClickListeners are now set to make a toast "Cheating is wrong"
i have declared a boolean value which is set to false, the boolean value is set to True and i save it in the bundle so that when the user rotates the screen , the value of the variable is not overwritten on onCreate(..) method being recalled..
I tried debugging with break points in eclipse , the value is not overridden still on main activity "Cheating is wrong" doesnt show up , it shows Correct or Incorrect..
QuizActivity : Launcher Activity
CheatActivity: Activity launched on onCreate
TrueFalse activity : creating array of objects with fields (question and answer)
Following is the code : QuizActivity.java (Launcher activity)
package com.mhrsolanki2020.geoquiz;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton, mFalseButton, mNextButton, mCheatButton;
private TextView mQuestionTextView;
private static final String KEY_INDEX = "index";
private static final String TAG = "QuizActivity";
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_oceans, true),
new TrueFalse(R.string.question_mideast, false),
new TrueFalse(R.string.question_africa, false),
new TrueFalse(R.string.question_americas, true),
new TrueFalse(R.string.question_asia, true) };
private int mCurrentIndex = 0;
private boolean mIsCheater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
mIsCheater=false;
}
});
mCheatButton = (Button) findViewById(R.id.cheat_button);
mCheatButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, CheatActivity.class);
boolean answer = mQuestionBank[mCurrentIndex].isTrueQuestion();
i.putExtra(CheatActivity.EXTRA_ANSWER_IS_TRUE, answer);
startActivityForResult(i, 0);
}
});
if (savedInstanceState != null)
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
updateQuestion();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX, mCurrentIndex);
}
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgement_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quiz, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null) {
return;
} else {
mIsCheater = data.getBooleanExtra(CheatActivity.EXTRA_ANSWER_SHOWN,
false);
Log.d(TAG, "Value of mIsCheater : " + mIsCheater);
}
}
}
The following is the code : CheatActivity.java
package com.mhrsolanki2020.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity {
public static final String EXTRA_ANSWER_IS_TRUE = "com.mhrsolanki2020.geoquiz.anwer_is_true ";
public static final String EXTRA_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_shown";
public static final String EXTRA_IS_ANSWER_SHOWN = "com.mhrsolanki2020.geoquiz.answer_is_shown";
boolean mCorrectAnswer;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsAnswerShown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mCorrectAnswer = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE,
false);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
if (savedInstanceState != null) {
mIsAnswerShown = savedInstanceState.getBoolean(
EXTRA_IS_ANSWER_SHOWN, false);
} else {
mIsAnswerShown = false;
}
mShowAnswer.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mCorrectAnswer) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
}
public void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
mIsAnswerShown = isAnswerShown;
data.putExtra(EXTRA_ANSWER_SHOWN, mIsAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(EXTRA_IS_ANSWER_SHOWN, mIsAnswerShown);
}
}
Following is the code : TrueFalse.java
package com.mhrsolanki2020.geoquiz;
public class TrueFalse {
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
http://developer.android.com/guide/topics/resources/runtime-changes.html check this link
For orientation support do this in manifest.xml
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
In Class file, override the onSaveInstanceState(Bundle outState).

Categories

Resources