i have a problem to send fbid to my server after logged out once. and if i want to login again it always send twice request and start the activity twice.
MainActivity.java:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("TheGaffer", "ONCREATE");
mFacebook = new Facebook(APP_ID);
SessionStore.restore(mFacebook, this);
setContentView(R.layout.login_view);
mLoginButton = (LoginButton) findViewById(R.id.login);
SessionEvents.addAuthListener(new SampleAuthListener());
mLoginButton.init(this, mFacebook);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
new fbRequest().execute("/user_profiles/registerUser");
}
private class fbRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
progressDialog = ProgressDialog.show(TheGaffer.this , null,
"Loading...");
}
protected String doInBackground(String... urls) {
String fbid = null;
Bundle params = new Bundle();
params.putString("fields", "id,name");
try {
JSONObject jsonObjSend = new JSONObject();
JSONObject fbData = new JSONObject(mFacebook.request("me", params));
fbid = fbData.getString("id");
jsonObjSend.put("fbid", fbData.getString("id"));
jsonObjSend.put("username", fbData.getString("name"));
jsonObjSend.put("playerPhoto", "http://graph.facebook.com/"+ fbData.getString("id") +"/picture");
HttpClient.SendHttpPost(urls[0], jsonObjSend);
} catch (Exception e) {
Log.e("FACEBOOK", "Error parsing data " + e.toString());
}
return fbid;
}
#Override
protected void onPostExecute(String fbid) {
Toast.makeText(getApplicationContext(), "Login successful", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
Intent intent = new Intent(TheGaffer.this, TeamActivity.class);
intent.putExtra("fbid", fbid);
startActivity(intent);
}
}
TeamActivity.java:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_create_team:
intent = new Intent(TeamActivity.this, CreateTeam.class);
return true;
case R.id.menu_logout:
Log.i("Logout", "Logged out");
Intent intent = new Intent(TeamActivity.this, TheGaffer.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Once I was trapped in similar situation where Activity call twice one after another.
To avoid this after lots of research I find a very easy solution.
May be solution is not perfect but works for me
in manifest.xml file
in your activity just add
android:launchMode="singleTask"
Related
i searched every directory and i dont see problem, please help me.
BlockquoteProcess:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setVisibility(int)' on a null object reference
at com.example.projectmanagement.wallet.CreateCashActivity.setViewOrUpdateWallet(CreateCashActivity.java:58)
at com.example.projectmanagement.wallet.CreateCashActivity.onCreate(CreateCashActivity.java:46)
And my code:
public class CreateCashActivity extends AppCompatActivity {
private EditText inputWalletTitle, inputWalletSubtitle, inputWalletText;
private Wallet alreadyAvailableWallet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_wallet);
ImageView imageBack = findViewById(R.id.imageBack);
imageBack.setOnClickListener(v -> onBackPressed());
inputWalletTitle = findViewById(R.id.inputWalletTitle);
inputWalletSubtitle = findViewById(R.id.inputWalletSubtitle);
inputWalletText = findViewById(R.id.inputWalletText);
Button save_btn = findViewById(R.id.save_btn);
save_btn.setOnClickListener(v -> saveWallet());
ImageView imageSave = findViewById(R.id.imageSave);
imageSave.setOnClickListener(v -> saveWallet());
if (getIntent().getBooleanExtra("isViewOrUpdate", false)) {
alreadyAvailableWallet = (Wallet) getIntent().getSerializableExtra("wallet");
setViewOrUpdateWallet();
}
}
private void setViewOrUpdateWallet() {
inputWalletTitle.setText(alreadyAvailableWallet.getTitle());
inputWalletSubtitle.setText(alreadyAvailableWallet.getSubtitle());
inputWalletText.setText(alreadyAvailableWallet.getWalletText());
if (alreadyAvailableWallet != null) {
this.findViewById(R.id.layoutDeleteWallet).setVisibility(View.VISIBLE);
}
}
private void saveWallet() {
if (inputWalletTitle.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Uzupełnij kwotę oraz walutę!", Toast.LENGTH_SHORT).show();
return;
}
if (inputWalletSubtitle.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Brak zlecenia!", Toast.LENGTH_SHORT).show();
return;
}
if (inputWalletText.getText().toString().trim().isEmpty()) {
Toast.makeText(this, "Brak opisu wydatku!", Toast.LENGTH_SHORT).show();
return;
}
final Wallet wallet = new Wallet();
wallet.setTitle(inputWalletTitle.getText().toString());
wallet.setSubtitle(inputWalletSubtitle.getText().toString());
wallet.setWalletText(inputWalletText.getText().toString());
if (alreadyAvailableWallet != null) {
wallet.setId(alreadyAvailableWallet.getId());
}
#SuppressLint("StaticFieldLeak")
class SaveWalletTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
WalletDatabase.getDatebase(getApplicationContext()).walletDao().insertWallet(wallet);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
}
new SaveWalletTask().execute();
}
public void deleteText(View view) {
final LinearLayout layoutMiscellcash = findViewById(R.id.layoutDeleteWallet);
layoutMiscellcash.findViewById(R.id.layoutDeleteWallet).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
#SuppressLint("StaticFieldLeak")
class DeleteWalletTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
WalletDatabase.getDatebase(getApplicationContext()).walletDao()
.deleteWallet(alreadyAvailableWallet);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent intent = new Intent();
intent.putExtra("isWalletDeleted", true);
setResult(RESULT_OK, intent);
finish();
}
}
new DeleteWalletTask().execute();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data != null) {
}
}
}
}
Logcat show line 58 and 46, this is:
this.findViewById(R.id.layoutDeleteWallet).setVisibility(View.VISIBLE);
and:
if (getIntent().getBooleanExtra("isViewOrUpdate", false)) { alreadyAvailableWallet = (Wallet) getIntent().getSerializableExtra("wallet"); setViewOrUpdateWallet(); }
I dont see problem in this. Please help.
all of you great developers, which I'm not, since I'm posting this question ;-)
I have a site with a to-do list where you can log in to Google. Now I want to make an Android app to access my DB on my site. I have the login with Google part correct and from that login activity, I switch to the activity (via intent, that's how I know I'm logged in correctly, cause the intent is only started when logged in) to display my to-do list. This is where I'm stuck. I can't seem to fetch the data from the DB, even though I'm logged in. I searched a bit online (watched a few hours of youtube video on the topic, and also searched StackOverflow, the internet in general and the Google developer pages), but no result. I'm guessing I have to pass on the token from the login activity to the other, but other than that, I just don't know and I'm hoping someone of you can point me in the right direction. Extra info: site is written in PHP with PDO for DB functions and MySQL DB. I also managed to get the JSON output on the site. In the android app, I also use Volley and it's written in Java (not Kotlin). I would really appreciate the help and if you need more info (or maybe a part of the code), be sure to ask.
Regards
Christophe
Edit: hereby the requested code:
LoginActivity:
package package_name;
some imports...
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "Scorpio To Do Login: ";
GoogleSignInOptions gso;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private int RC_SIGN_IN = 6;
private static final String URL_DATA = "https://some.url.be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
#Override
protected void onStart() {
super.onStart();
// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount account) {
Log.w(TAG, "account = " + account);
if(account == null){
// Set the dimensions of the sign-in button.
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
signInButton.setVisibility(View.VISIBLE);
} else {
Context context = LoginActivity.this;
/* This is the class that we want to start (and open) when the button is clicked. */
Class destinationActivity = TaskActivity.class;
/*
* Here, we create the Intent that will start the Activity we specified above in
* the destinationActivity variable. The constructor for an Intent also requires a
* context, which we stored in the variable named "context".
*/
Intent startChildActivityIntent = new Intent(context, destinationActivity);
/*
* Once the Intent has been created, we can use Activity's method, "startActivity"
* to start the ChildActivity.
*/
startActivity(startChildActivityIntent);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
Log.d("Token: ", idToken);
// Signed in successfully, show authenticated UI.
updateUI(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
}
TaskActivity:
package package_name;
some imports...
public class TaskActivity extends AppCompatActivity {
private static final String URL_DATA = "https://some.url.be";
private RecyclerView recyclerView;
private RecyclerView.Adapter scorpioAdapter;
private List<ListItem> listItems;
String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
}
/*REAL DATA*/
/*try instead of loadRecyclerViewData*/
public void getJSON(View view){
new BackgroundTask().execute();
}
/*end try*/
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(s);
for(int i=0;i<jsonArray.length();i++){
JSONObject o = jsonArray.getJSONObject(i);
int id = o.getInt("id");
String name = o.getString("name");
int done = o.getInt("done");
String reminderDate = o.getString("reminderdate");
String reminderTime = o.getString("remindertime");
ListItem item = new ListItem(id, name, done, reminderDate, reminderTime);
listItems.add(item);
}
scorpioAdapter = new ScorpioAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(scorpioAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
/*END REAL DATA*/
/* things I tried*/
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "https://some.url.be";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Log.i("Scorpio To Do: ", result);
TextView name = (TextView) findViewById(R.id.name);
name.setText(result);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/*end try*/
}
I am trying to send a broadcast receiver from a service and i have a issue, the receiver leak and i don't know why.
Here is the code:
public class CameraCapture extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 30;
String URL;
VolleyService mVolleyService;
IResult mResultCallback = null;
final String POSTREQUEST = "POSTCALL";
Map<String, String> params;
String token;
BroadcastReceiver receiver;
IntentFilter filter;
MyReceiver reciver;
boolean mBounded;
GoogleLocation mlocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
token = checkForToken();
URL = "http://10.0.2.2:3000/fotos/Tulipa";
filter = new IntentFilter("com.myapp.LOCATION_CHANGED");
reciver = new MyReceiver();
registerReceiver(reciver,filter);
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.jpg";
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_IMAGE_CAPTURE);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, GoogleLocation.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
}
public void onResume() {
super.onResume();
Log.d("RESUME","RESUME");
reciver = new MyReceiver();
registerReceiver(reciver, filter);
}
public void onPause() {
super.onPause();
if(reciver != null){
unregisterReceiver(reciver);
reciver= null;
}
}
public void onStop() {
super.onStop();
if(mBounded) {
unbindService(mConnection);
mBounded = false;
}
}
private byte[] encodeImage(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
return b;
}
private void sendImage(byte[] b) {
ImageStore.getInstance().setCapturedPhotoData(b);
mlocation.getBroadcastData();
Intent i = new Intent(CameraCapture.this, SimiliarPhotos.class);
startActivity(i);
finish();
//inicialize a map with pair key value
//params = new HashMap<String, String>();
// Add form fields to the map
//GoogleLocation l = new GoogleLocation(this);
//l.getPosition();
//Log.d("myLat",String.valueOf(l.getLat()));
//params.put("base64", encodedImage);
//params.put("token",token);
//Log.d("latitudeOP",String.valueOf(l.getLat()));
//JSONObject sendObj = new JSONObject(params);
//initVolleyCallback();
//mVolleyService = new VolleyService(mResultCallback, this);
//mVolleyService.postDataVolley(POSTREQUEST, URL, sendObj);
}
public void showToast(String message) {
Toast toast = Toast.makeText(this, message, Toast.LENGTH_LONG);
toast.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 30: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(CameraCapture.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
}
return;
}
}
}
void initVolleyCallback() {
mResultCallback = new IResult() {
#Override
public void notifySuccess(String requestType, JSONObject response) {
}
#Override
public void notifySuccess(String requestType, JSONArray response) {
}
#Override
public void notifyError(String requestType, VolleyError error) {
String body;
if (error.networkResponse.data != null) {
String statusCode = String.valueOf(error.networkResponse.statusCode);
try {
body = new String(error.networkResponse.data, "UTF-8");
JSONObject jsonObj = new JSONObject(body);
Log.d("body", String.valueOf(jsonObj.get("message")));
showToast(String.valueOf(jsonObj.get("message")));
} catch (UnsupportedEncodingException e) {
showToast("You need to connect to the internet!");
} catch (JSONException e) {
Log.d("json:", "problems decoding jsonObj");
}
}
}
};
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mlocation = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
GoogleLocation.LocalBinder mLocalBinder = (GoogleLocation.LocalBinder)service;
mlocation = mLocalBinder.getServerInstance();
}
};
as you guys can see i register the receiver 2 times, oncreate and onResume, and then i destroy it onStop.
The problem is you are registering it twice. remove the code from onCreate and keep it only in onResume. Also if you are registering it in onResume then unRegister it in onPause to match the lifecycle events properly.
Always register receiver in onStart() and unregister in onStop().
Since you registering receiver in onCreate(), you have to unregister in onDestroy() as well as there is a chance that activity ends up with only onCreate() and onDestroy() call backs.
Do not forget to unregister a dynamically registered receiver by using Context.unregisterReceiver() method. If you forget this, the Android system reports a leaked broadcast receiver error. For instance, if you registered a receive in onResume() methods of your activity, you should unregister it in the onPause() method.
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec(TAB_NEWS).setIndicator(TAB_NEWS).setContent(new Intent(this, NewsActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_BBS).setIndicator(TAB_BBS).setContent(new Intent(this, BBSActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_CATEGORY).setIndicator(TAB_CATEGORY).setContent(new Intent(this, CategoryActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_DISCOVER).setIndicator(TAB_DISCOVER).setContent(new Intent(this, DiscoverActivity.class)));
mTabHost.addTab(mTabHost.newTabSpec(TAB_MINE).setIndicator(TAB_MINE).setContent(new Intent(this, MineActivity.class)));
Because a reason, i use the TabActivity, but the system's permission dialog can't show in targetSdk23.
for example: in NewsActivity, BBSActivity,CategoryActivity,DiscoverActivity,MineActivity, all cant show.
please help me, thanks~
for example DiscoverActivity:
public class DiscoverActivity extends BaseActivity implements View.OnClickListener{
private RelativeLayout near, plate, search, rate, oil, two_dimension_code, rl_activity, coupon;
private TextView tvActivityTitle;
private String url;
private LoadDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discover);
GoogleAnalyticsUtil.doGoogleAnalytics();
initView();
initEvent();
}
private void initView() {
// TODO Auto-generated method stub
near = (RelativeLayout) findViewById(R.id.discover_near);
plate = (RelativeLayout) findViewById(R.id.discover_plate);
search = (RelativeLayout) findViewById(R.id.discover_search);
rate = (RelativeLayout) findViewById(R.id.discover_rate);
oil = (RelativeLayout) findViewById(R.id.discover_oil);
two_dimension_code = (RelativeLayout) findViewById(R.id.rl_twodimension_code);
rl_activity = (RelativeLayout) findViewById(R.id.rl_activity);
coupon = (RelativeLayout) findViewById(R.id.rl_coupon);
tvActivityTitle = (TextView) findViewById(R.id.tv_activity_title);
}
private void initEvent() {
near.setOnClickListener(this);
plate.setOnClickListener(this);
search.setOnClickListener(this);
rate.setOnClickListener(this);
oil.setOnClickListener(this);
two_dimension_code.setOnClickListener(this);
rl_activity.setOnClickListener(this);
coupon.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final Intent intent = new Intent();
switch (v.getId()) {
case R.id.discover_near:
GoogleAnalyticsUtil.doGoogleActionAnalytics(GoogleAnalyticsConstant.ActionEvent.NEARPEOPLE_ACTION);
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
intent.setClass(this, LoginActivity.class);
startActivity(intent);
} else {
intent.setClass(this, NearbyActivity.class);
startActivity(intent);
}
break;
case R.id.discover_plate:
intent.setClass(this, ForumActivity.class);
startActivity(intent);
break;
case R.id.discover_search:
intent.setClass(this, TopicSearchActivity.class);
startActivity(intent);
break;
case R.id.discover_rate:
intent.setClass(this, RateActivity.class);
startActivity(intent);
break;
case R.id.discover_oil:
intent.setClass(this, OilActivity.class);
startActivity(intent);
break;
case R.id.rl_twodimension_code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
DialogUtil.getInstance().showPermissionDialog(this, "permission");
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
} else {
intent.setClass(DiscoverActivity.this, CaptureActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
break;
case R.id.rl_activity:
intent.setClass(this, WebViewActivity.class);
intent.putExtra("url", url);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
case R.id.rl_coupon:
intent.setClass(this, GroupBuyListActivity.class);
startActivity(intent);
break;
}
}
private void loadActivity() {
Map<String, String> mp = new HashMap<String, String>();
Okhttp.getIntance().post(Api.REAL_URL, Api.YORKBBS_CMS_TXTSETTING, mp, new StringCallback() {
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
if (jsonObject.has("list")) {
rl_activity.setVisibility(View.VISIBLE);
String list = jsonObject.get("list").toString();
List<Discoverac> listObj = new Gson().fromJson(list, new TypeToken<List<Discoverac>>() {
}.getType());
if (listObj != null && listObj.size() > 0) {
tvActivityTitle.setText(listObj.get(0).getTxt());
url = listObj.get(0).getUrl();
}
}
}
rl_activity.setVisibility(View.GONE);
}
});
}
private void check(String ticket) {
Map<String, String> mp = new HashMap<String, String>();
mp.put("sessionkey", ShareProUtils.getLoginSession(this));
mp.put("code", ticket);
mp.put("merchantid", ShareProUtils.getUid(this));
Okhttp.getIntance().post(Api.GROUPBUY_URL, Api.GROUPON_CHECK, mp, new StringCallback() {
#Override
public void onBefore(Request request) {
super.onBefore(request);
dialog = DialogUtil.getInstance().showLoadDialog(DiscoverActivity.this, "正在验证...");
}
#Override
public void onError(Call call, Exception e) {
}
#Override
public void onResponse(String response) {
if (!TextUtils.isEmpty(response)) {
String result = ParamUtils.ConvertData(response);
GrouponDetailResponse response1 = new Gson().fromJson(result,GrouponDetailResponse.class);
if (response1.getFlag().equals("0")){
Intent intent = new Intent(DiscoverActivity.this, TicketCheckSuccessActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(DiscoverActivity.this, TicketCheckFailActivity.class);
startActivity(intent);
}
} else {
TipsToast.show(DiscoverActivity.this, "error");
}
}
#Override
public void onAfter() {
DialogUtil.getInstance().dissMissDialog(dialog);
super.onAfter();
}
});
}
#Override
protected void onResume() {
super.onResume();
if (isNet()) {
loadActivity();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 1) {
Bundle bundle = data.getExtras();
String result = bundle.getString("result");
if (!TextUtils.isEmpty(result)) {
if (result.contains("code")) {
if (TextUtils.isEmpty(ShareProUtils.getUid(this))) {
Intent login = new Intent(this, LoginActivity.class);
startActivity(login);
return;
}
result = result.replaceAll("http://www.yorkbbs.ca\\?yorkbbscode=","");
check(result);
} else {
Intent intent = new Intent(this, WebViewActivity.class);
intent.putExtra("url", result);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
} else {
TipsToast.show(this, "scan error");
}
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
TabActivity is now deprecated. To Create Tab you have to create it using Fragment and ViewPager.
Here is example to create Tab using Fragment and ViewPager .
see Exmaple here : http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/
Another class calls the GridView class below that is populated with images from a parse server, if a user clicks on a grid item, it starts the same GridView class with different bundled strings so it can pull from a different parse database class. Now at this point, when a user clicks an GridView item (from the 2nd gridview that was set up), I want it to start a different activity class.
I tried doing an if/else if statement in the onItemClick that takes the "PARSE_CLASS" bundled string but I can't seem to get that to work. I'm relatively new to android programming so I don't know the best way to do this.
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
gridView = (GridView) findViewById(R.id.gridView);
itemGridAdapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(itemGridAdapter);
new RemoteDataTask().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
}
});
}//end onCreate method
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
gridView = (GridView) findViewById(R.id.gridView);
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}
This is what I tried. When I tried this, the second GridView wouldn't load. So I'm guessing I'm unable to retrieve the "PARSE_CLASS" bundled string the second time around.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent i = getIntent();
Bundle itemExtras = i.getExtras();
final String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = extras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
if (parseClass == "Categories") {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", "Items");
t.putExtras(extras);
startActivity(t);
} else if(parseClass == "Items"){
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
ANSWER
Someone on reddit's learn programming was nice enough to point out that I had an issue with string comparisons. had to use
if(parseClass.equals("Categories")){}
instead of
if(parseClass == "Categories"){}
I feel like an idiot, hopefully someone else benefits from this long disastrous effort.
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
Intent t = getIntent();
Bundle itemExtras = t.getExtras();
String activeSupplier = itemExtras.getString("SUPPLIER");
String parseClass = itemExtras.getString("PARSE_CLASS");
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Log.i("AppInfo", parseClass);
if (parseClass.equals("Categories")) {
Log.i("AppInfo", parseClass);
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
String categoryName = categoryNameArrayList.get(position);
itemExtras.putString("SUPPLIER", activeSupplier);
itemExtras.putString("PARSE_CLASS", "Items");
itemExtras.putString("CATEGORY_NAME", categoryName);
t.putExtras(itemExtras);
startActivity(t);
} else if (parseClass.equals("Items")) {
Intent t = new Intent(getApplicationContext(), ItemDisplay.class);
//extras.putString("SUPPLIER", activeSupplier);
//extras.putString("PARSE_CLASS", "Items");
//t.putExtras(extras);
startActivity(t);
}
}
});
public class DisplayGrid extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
GridView gridView = null;
List<ParseObject> obj;
ProgressDialog loadProgress;
GridViewAdapter adapter;
Bundle extras = new Bundle();
GridViewAdapter itemGridAdapter;
private List<ImageList> imageArrayList = null;
private List<String> categoryNameArrayList = null;
String activeSupplier;
String parseClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ws_display_grid);
imageArrayList = new ArrayList<ImageList>();
categoryNameArrayList = new ArrayList<String>();
Intent i = getIntent();
if (null != i) {
Bundle itemExtras = i.getExtras();
activeSupplier = itemExtras.getString("SUPPLIER");
parseClass = itemExtras.getString("PARSE_CLASS");
}
RemoteDataTask remoteDataAsync = new RemoteDataTask();
remoteDataAsync.execute();
if(remoteDataAsync.getStatus() == AsyncTask.Status.PENDING){
// My AsyncTask has not started yet
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.RUNNING){
// My AsyncTask is currently doing work in doInBackground()
}
if(remoteDataAsync.getStatus() == AsyncTask.Status.FINISHED){
// My AsyncTask is done and onPostExecute was called
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent t = new Intent(getApplicationContext(), DisplayGrid.class);
extras.putString("SUPPLIER", activeSupplier);
extras.putString("PARSE_CLASS", parseClass);
t.putExtras(extras);
startActivity(t);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
//RemoteDataTask
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
loadProgress = new ProgressDialog(DisplayGrid.this);
loadProgress.setTitle("Images");
loadProgress.setMessage("Loading...");
loadProgress.setIndeterminate(false);
loadProgress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Intent i = getIntent();
Bundle extras = i.getExtras();
String parseClass = extras.getString("PARSE_CLASS");
String activeSupplier = extras.getString("SUPPLIER");
String category;
ParseQuery<ParseObject> query = new ParseQuery<>(parseClass);
query.whereEqualTo("username", activeSupplier);
obj = query.find();
if (parseClass == "Items") {
category = extras.getString("CATEGORY");
query.whereEqualTo("category", category);
}
for (ParseObject categories : obj) {
//get image
ParseFile image = (ParseFile) categories.get("image");
ImageList gridBlock = new ImageList();
gridBlock.setImage(image.getUrl());
imageArrayList.add(gridBlock);
Log.i("AppInfo", "image sent to imageArrayList");
String categoryName = null;
//get category name
if (categoryName == null) {
} else {
categoryName = categories.getString("categoryName");
categoryNameArrayList.add(categoryName);
Log.i("AppInfo", categoryName);
}
}
} catch (ParseException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
adapter = new GridViewAdapter(DisplayGrid.this, imageArrayList);
gridView.setAdapter(adapter);
loadProgress.dismiss();
Log.i("AppInfo", "CategoryGrid Populated");
}//end onCreate method
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
try {
Bitmap bitmapImage =
MediaStore.Images.Media.getBitmap
(this.getContentResolver(), selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//convert to parse file
ParseFile file = new ParseFile("Img.png", byteArray);
ParseObject object = new ParseObject("Categories");
object.put("username", ParseUser.getCurrentUser().getUsername());
object.put("image", file);
object.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (e == null) {
Toast.makeText(getApplication().getBaseContext(), "Your image has been saved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
});
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(), "Upload failed, please try again", Toast.LENGTH_SHORT).show();
}
}
}
//begin getTitle method
//begin createMenu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.options, menu);
return (super.onCreateOptionsMenu(menu));
}
//end createMenu
//begin onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.manufacturers) {
Intent i = new Intent(getApplicationContext(), SupplierList.class);
startActivity(i);
return true;
} else if (item.getItemId() == R.id.add) {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 1);
return true;
} else if (item.getItemId() == R.id.sign_out) {
ParseUser.logOut();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
return true;
}
return (super.onOptionsItemSelected(item));
}
//end onOptionsItemSelected
}