Related
I am having this following error. I added constructor on DailyVerseFragment. But still it doesn't work.
I am having this issues for more than one week.
Fatal Exception: java.lang.RuntimeException
Unable to start activity ComponentInfo{com.donghyouny.biblecard/com.donghyouny.biblecard.MainActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.donghyouny.biblecard.DailyVerseFragment: could not find Fragment constructor
package com.donghyouny.biblecard;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.view.ViewGroup;
import android.widget.Button;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.core.view.GravityCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, FragmentCallback {
Toolbar toolbar;
CardFragment cardFargment;
DailyVerseFragment dailyVerseFragment;
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dailyVerseFragment = new DailyVerseFragment();
// mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
contextOfApplication = getApplicationContext();
toolbar.setTitle("Draw Verse Card");
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();
drawer.openDrawer(GravityCompat.START);
cardFargment = new CardFragment();
Calendar mCalendar = Calendar.getInstance();
/*mCalendar.set(Calendar.HOUR_OF_DAY, 01);
mCalendar.set(Calendar.MINUTE, 01);
mCalendar.set(Calendar.SECOND, 0);*/
mCalendar.set(Calendar.HOUR_OF_DAY, 0);
if(mCalendar.before(Calendar.getInstance())){ // if it's in the past, increment
mCalendar.add(Calendar.DATE, 1);
}
// PackageManager pm = this.getPackageManager();
// ComponentName receiver = new ComponentName(this, DeviceBootReceiver.class);
Intent alarmIntent = new Intent(this, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (alarmManager != null) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, mCalendar.getTimeInMillis(), pendingIntent);
}
}
// 부팅 후 실행되는 리시버 사용가능하게 설정
/* pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
// setAlarm(mCalendar);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().beginTransaction().add(R.id.container, cardFargment).commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if(drawer.isDrawerOpen(GravityCompat.START)){
drawer.closeDrawer(GravityCompat.START);
}else{
// super.onBackPressed();
AlertDialog.Builder alBuilder = new AlertDialog.Builder(this, R.style.AlertDialogCustom);
alBuilder.setMessage("Do you want to exit?");
// "예" 버튼을 누르면 실행되는 리스너
alBuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish(); // 현재 액티비티를 종료한다. (MainActivity에서 작동하기 때문에 애플리케이션을 종료한다.)
}
});
// "아니오" 버튼을 누르면 실행되는 리스너
alBuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
return; // 아무런 작업도 하지 않고 돌아간다
}
});
alBuilder.setTitle("Program Exit");
alBuilder.show(); // AlertDialog.Bulider로 만든 AlertDialog를 보여준다.
}
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Bundle bundle = getBundle(menuItem);
// onFragmentSelected(0, bundle);
int id = menuItem.getItemId();
if(id == R.id.menu1){
onFragmentSelected(0, bundle);
}else if(id == R.id.menu2){
onFragmentSelected(1, bundle);
}else if(id == R.id.menu3) {
onFragmentSelected(2, bundle);
}else if(id == R.id.menu4) {
onFragmentSelected(3, bundle);
}else if(id == R.id.menu5) {
onFragmentSelected(4, bundle);
}else if(id == R.id.menu6) {
onFragmentSelected(5, bundle);
}else if(id == R.id.menu7) {
onFragmentSelected(6, bundle);
}else if(id == R.id.menu8) {
onFragmentSelected(7, bundle);
}else if(id == R.id.menu9) {
onFragmentSelected(8, bundle);
}else if(id == R.id.menu10) {
onFragmentSelected(9, bundle);
}else if(id == R.id.menu11) {
onFragmentSelected(10, bundle);
}else if(id == R.id.menu12) {
onFragmentSelected(11, bundle);
}else if(id == R.id.menu13) {
onFragmentSelected(12, bundle);
}else if(id == R.id.menu14) {
onFragmentSelected(13, bundle);
}else if(id == R.id.menu15) {
onFragmentSelected(14, bundle);
}else if(id == R.id.menu16) {
onFragmentSelected(15, bundle);
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private Bundle getBundle(#NonNull MenuItem menuItem) {
Bundle bundle = new Bundle();
bundle.putString("value", menuItem.getTitle().toString());
return bundle;
}
#Override
public void onFragmentSelected(int position, Bundle bundle) {
String value = bundle.getString("value");
Fragment curFragment = null;
if(position == 0){
curFragment = new CardFragment();
toolbar.setTitle(value);
}else if(position==1){
curFragment = new DailyVerseFragment(toolbar);
//toolbar.setTitle(value);
}else if(position>=2){
curFragment = new Fragment1(value);
toolbar.setTitle(value);
}
// toolbar.setTitle(value);
getSupportFragmentManager().beginTransaction().replace(R.id.container, curFragment).commit();
}
// a static variable to get a reference of our application context
public static Context contextOfApplication;
public static Context getContextOfApplication()
{
return contextOfApplication;
}
}
package com.donghyouny.biblecard;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.gms.ads.AdView;
public class DailyVerseFragment extends Fragment {
private ImageView imageView;
private TextView bibleType;
private TextView verse;
private TextView content;
public Bible bible;
private SharedPreferences checkDialog;
private SharedPreferences saveDialog;
private SharedPreferences shareDialog;
private ImageView like;
private ImageView check;
private ImageView save;
private TextView likecount, savecount, link;
public static final int REQUEST_CODE = 101;
private String key;
private Toolbar toolbar;
private boolean flag;
private AdView mAdView;
private String categoryName;
private DrawableImage DrawbleImage;
private AlertReceiver AlertReceivr;
public DailyVerseFragment(){}
public DailyVerseFragment(Toolbar value) {
this.toolbar = value;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Activity a = getActivity();
if (a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.fragment_daily_verse, container, false);
// toolbar = rootView.findViewById(R.id.toolbar);
// ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
verse = rootView.findViewById(R.id.verse);
content = rootView.findViewById(R.id.content);
imageView = rootView.findViewById(R.id.imageView);
save = rootView.findViewById(R.id.save);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("bibleNum", Context.MODE_PRIVATE);
final int bibleNum = sharedPreferences.getInt("bibleNum", 1);
Log.d("DailyVerseNum", String.valueOf(bibleNum));
MyDatabaseHelper db = new MyDatabaseHelper(getActivity());
Cursor cursor = db.readDailyCardData(bibleNum);
cursor.moveToFirst();
bible = new Bible();
Log.d("cursorid", String.valueOf(cursor.getInt(0)));
bible.setId(cursor.getInt(0));
bible.setVerse(cursor.getString(1));
bible.setContent(cursor.getString(2));
bible.setNum(cursor.getInt(3));
bible.setCnum(cursor.getInt(4));
bible.setVnum(cursor.getInt(5));
bible.setImage(cursor.getBlob(6));
bible.setTimestamp(cursor.getString(7));
Log.d("content", bible.getContent());
Log.d("bible.getCnum", String.valueOf(bible.getCnum()));
Cursor cursor1 = db.getCategoryName(bible.getCnum());
cursor1.moveToFirst();
categoryName = cursor1.getString(0);
display();
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveDialog = getActivity().getSharedPreferences("saveDialog", Context.MODE_PRIVATE);
boolean isFirst = saveDialog.getBoolean("first", true);
if(isFirst){
saveDialogPopup();
}else{
onSave(bible);
}
}
});
setHasOptionsMenu(true);
return rootView;
}
private void checkMethod(Bible bible) {
MyDatabaseHelper db = new MyDatabaseHelper(getContext());
db.updateData(bible);
}
private void checkDialogPopup() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Check Button");
builder.setMessage("If you want to specify which verse is already read, this button will move the one you read to the lowest of the previously show list. But once you click this button, you cannot revert it. Do you want to proceed?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"You select 'Yes'.",Toast.LENGTH_SHORT).show();
checkMethod(bible);
}
});
builder.setNegativeButton("Don't show this message, again.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = checkDialog.edit();
editor.putBoolean("firstTime", false);
editor.commit();
Toast.makeText(getContext(),"You select 'Don't show this message, again.'",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
private void onSave(Bible bible) {
Log.d("getId", String.valueOf(bible.getId()));
MyDatabaseHelper db1 = new MyDatabaseHelper(getContext());
Cursor cursor = db1.getSaveDataById(bible.getId());
flag=true;
cursor.moveToFirst();
Log.d("countcursor", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.moveToFirst()) {
Toast.makeText(getContext(),"It is already saved.",Toast.LENGTH_SHORT).show();
flag = false;
}else if(flag){
db1.insertToSave(bible);
cursor.close();
}
}
private void saveDialogPopup() {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Save Button");
builder.setMessage("If you select this button, the verse you read will be saved and if you want to see that verse that you saved, you should go to verse list and on the top right, you will see yellow folder icon. If you click that icon. It will take you to 'favorite bible verse'. If you want to save?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
onSave(bible);
}
});
builder.setNegativeButton("Don't show this message, again.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = saveDialog.edit();
editor.putBoolean("first", false);
editor.commit();
Toast.makeText(getContext(),"You select not \'Don\'t show this message, again\'.",Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
double getScreenInches() {
DisplayMetrics dm = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
double wi = (double) width / (double) dm.xdpi;
double hi = (double) height / (double) dm.ydpi;
double x = Math.pow(wi, 2);
double y = Math.pow(hi, 2);
double screenInches = Math.sqrt(x + y);
return screenInches;
}
private void display(){
DisplayMetrics metrics = new DisplayMetrics();
WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(metrics);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
params.width = metrics.widthPixels;
params.height = (int)(metrics.heightPixels/2.8);
Log.d("width", String.valueOf(params.width));
Log.d("height", String.valueOf(params.height));
imageView.setLayoutParams(params);
Glide.with(getContext()).load(bible.getImage()).apply(new RequestOptions().centerCrop()).into(imageView);
//imageView.setImageResource(R.drawable.church);
verse.setText(bible.getVerse().toString());
content.setText(bible.getContent().toString());
Log.d("content", bible.getContent().toString());
int inch = (int)( getScreenInches()+0.5 );
Log.d("inch", String.valueOf(3*inch));
//content.setTextSize(3*inch);
toolbar.setTitle(categoryName);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.share_actions, menu);
}
public void shareDialogPopup(){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialogCustom);
builder.setTitle("Share Button");
builder.setMessage("You can share bible verse that you read by clicking this button. Do you want to proceed?");
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(),"You select \'Yes\'.",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, bible.getVerse()+"\n"+bible.getContent()+"\n"+"https://play.google.com/store/apps/details?id=the.holy.catholic.bible");
Intent chooser = Intent.createChooser(intent, "Share");
startActivity(chooser);
}
});
builder.setNegativeButton("Don\'t show this message, again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
SharedPreferences.Editor editor = shareDialog.edit();
editor.putBoolean("printMsg", false);
editor.commit();
Toast.makeText(getContext(),"You select not \'Don\'t show this message, again\'.",Toast.LENGTH_SHORT).show();
}
});
/*AlertDialog alert = builder.create();
alert.show();
alert.getWindow().getAttributes();
TextView textView = (TextView) alert.findViewById(android.R.id.message);
textView.setTextSize(15);
Button btn1 = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
Button btn2 = alert.getButton(DialogInterface.BUTTON_POSITIVE);
btn1.setTextSize(12);
btn2.setTextSize(12);*/
builder.show();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
shareDialog = getActivity().getSharedPreferences("shareDialog", Context.MODE_PRIVATE);
boolean printMsg = shareDialog.getBoolean("printMsg", true);
if(printMsg){
shareDialogPopup();
}else{
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, bible.getVerse()+"\n"+bible.getContent()+"\n"+"https://play.google.com/store/apps/details?id=the.holy.catholic.bible");
Intent chooser = Intent.createChooser(intent, "Share");
startActivity(chooser);
break;
}
}
return super.onOptionsItemSelected(item);
}
}
The Problem that caused your crash is that you want to instantiate your fragment with a constructor with parameter. but you in android you should create fragment with a non parameter constructor.
so how to solve this problem to pass parameters in to your fragment:
in DailyVerseFragment :
public static DailyVerseFragment newInstance(String myString) {
DailyVerseFragment myFragment = new DailyVerseFragment();
Bundle args = new Bundle();
args.putString("key", myString);
myFragment.setArguments(args);
return myFragment;
}
and in onCreate() function of fragment get it like :
getArguments().getString("key");
and if you want to send Objects you can use putParcable/getParcable.
but my suggestion for you to get toolbar in your fragment is to access it in your fragment like this:
((AppCompatActivity) getActivity()).getSupportActionBar()
I want put edittext from first activity to new secondactivity view text.
What to do when I have an erro like this displayed in android monitor :
com.example.xx.DrawerAddAd.seeAdd(DrawerAddAd.java:129)
com.example.xx.DrawerAddAd.access$100(DrawerAddAd.java:40)
com.example.xx.DrawerAddAd$2.onClick(DrawerAddAd.java:116)
also:
Render problem:
Couldn't resolve resource #id/visible
Tip: Try to refresh the layout.
DrawerAddAd class code:
package com.example.xx.drawer;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import com.example.xx.R;
import com.example.xxx.model.POJO.view.ProductDetails;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import butterknife.BindView;
public class DrawerAddAd extends AppCompatActivity {
public static ArrayList<String> fragments = new ArrayList<>();
private final int REQUEST_CODE = 1;
private ImageButton camera_imageButton;
private Spinner spinner_category;
private Button button_seeAd_product;
private Button button_add_product;
#BindView(R.id.title_Ad_editText)
EditText titleAd_editText;
#BindView(R.id.text_Ad_editText)
EditText textAd_editText;
#BindView(R.id.price_editText)
EditText price_editText;
#BindView(R.id.checkBox_season)
CheckBox checkBox_season;
#BindView(R.id.checkBox_year)
CheckBox checkBox_year;
#BindView(R.id.checkBox_detail)
CheckBox checkBox_detail;
#BindView(R.id.checkBox_wholesale)
CheckBox checkBox_whoLesale;
private int REQUEST_CAMERA = 1, SELECT_FILE = 1;
private Button btnSelect;
private ImageView Image;
private String userChosenTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_add_ad);
final TextInputLayout title_ad_layout = (TextInputLayout) findViewById(R.id.add_title_ad_layout);
final TextInputLayout text_ad_layout = (TextInputLayout) findViewById(R.id.add_text_ad_layout);
final TextInputEditText title_Ad_editText = (TextInputEditText) findViewById(R.id.title_Ad_editText);
final TextInputEditText text_Ad_editText = (TextInputEditText) findViewById(R.id.text_Ad_editText);
setTextWatcher(title_Ad_editText, title_ad_layout);
setTextWatcher(text_Ad_editText, text_ad_layout);
spinner_category = (Spinner) findViewById(R.id.spinner_category);
button_seeAd_product = (Button) findViewById(R.id.button_seeAd_product);
button_add_product = (Button) findViewById(R.id.button_ad_product);
camera_imageButton = (ImageButton) findViewById(R.id.camera_imageButton);
camera_imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
button_seeAd_product.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean error = false;
if (TextUtils.isEmpty(title_Ad_editText.getText().toString())) {
title_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (TextUtils.isEmpty(text_Ad_editText.getText().toString())) {
text_ad_layout.setError(getString(R.string.empty_field));
error = true;
}
if (!error) {
seeAdd();
}
}
});
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.fragments, R.layout.support_simple_spinner_dropdown_item);
adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
spinner_category.setAdapter(adapter);
}
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
// ImageView imageView =
// String title = titleAd_editText.getText().toString();
// String text = textAd_editText.getText().toString();
// String price = price_editText.getText().toString();
//
//
// intent.putExtra("titleAdd", title);
// intent.putExtra("textAdd", text);
// intent.putExtra("price", price);
startActivity(intent);
}
private void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
switch (view.getId()) {
case R.id.checkBox_season:
if (checked) {
} else {
}
break;
case R.id.checkBox_year:
if (checked) {
} else {
}
break;
case R.id.checkBox_detail:
if (checked) {
} else {
}
break;
case R.id.checkBox_wholesale:
if (checked) {
} else {
}
break;
}
}
private void setTextWatcher(final TextInputEditText editText, final TextInputLayout inputLayout) {
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (inputLayout.isErrorEnabled()) {
inputLayout.setErrorEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
private void selectImage() {
final CharSequence[] items = {"Zrób zdjęcie", "Wybierz z katalogu", "Anuluj"};
AlertDialog.Builder builder = new AlertDialog.Builder(DrawerAddAd.this);
builder.setTitle("Dodaj zdjęcie");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Utility.checkPermission(DrawerAddAd.this);
if (items[item].equals("Zrób zdjęcie")) {
userChosenTask = "Zrób zdjęcie";
if (result)
cameraIntent();
} else if (items[item].equals("Wybierz z katalogu")) {
userChosenTask = "Wybierz z katalogu";
if (result)
galleryIntent();
} else if (items[item].equals("Anuluj")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
private void galleryIntent() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Wybierz plik"), SELECT_FILE);
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm = null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
Image.setImageBitmap(bm);
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Image.setImageBitmap(thumbnail);
}
}
ProductDetails class code:
package com.example.xxx.model.POJO.view;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import com.example.xxx.R;
public class ProductDetails extends AppCompatActivity {
private TextView title, text, price, date;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product_details);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
title = (TextView) findViewById(R.id.title_textView);
text = (TextView) findViewById(R.id.text_textView);
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
title.setText(title_textView);
text.setText(text_textView);
// price = (TextView) findViewById(R.id.price_textView);
// date = (TextView) findViewById(R.id.date_textView);
// String titleAdd = bundle.getString("titleAdd");
// String textAdd = bundle.getString("textAdd");
// String price = bundle.getString("price");
// title.setText(titleAdd);
// text.setText(textAdd);
// price.setText(price);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
}
}
I don't know what to do ...
Thanks, Slawek.
it means title_Ad_editText is null.
Check your xml file and title_Ad_editText variable.
couple things I could see, redo this:
private void seeAdd() {
Intent intent = new Intent(getApplicationContext(), ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
to this:
private void seeAdd() {
Intent intent = new Intent(DrawerAddAd.this, ProductDetails.class);
intent.putExtra("title",titleAd_editText.getText().toString());
intent.putExtra("text", textAd_editText.getText().toString());
then in your intent, you need to call the extra exactly as set, change this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("titleAdd");
String text_textView = intent.getStringExtra("textAdd");
to this:
Intent intent = getIntent();
// Bundle bundle = getIntent().getExtras();
String title_textView = intent.getStringExtra("title");
String text_textView = intent.getStringExtra("text");
I have probably invested about 10 hours on this mistake xD still cant find it :/
I have basically 3 layouts. The first layout is for the menu/home, the second is a quiz, and the third is the results screen. The problem right now is that I have no idea how to connect the button from the result screen. (has a button to go back to the menu layout). I dont know where I can add this:
Button haupt = (Button) findViewById(R.id.hauptmeldung);
haupt.setOnclickListener(this); //this refers to the one in the QuizActivty,
abschlusslayout = result screen
activtymain = home/menu layout
quizlayout = quiz
Here are my 3 java files:
MainActivity (QuizActivity):
package at.lorenzdirry.philosophenquiz;
import at.lorenzdirry.philosophenquiz.R.id;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class QuizActivity extends Activity implements android.view.View.OnClickListener {
Spiellogik spiel;
Button startbut1;
View myView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myView = (View)findViewById(id.mainlay);
startbut1= (Button)findViewById(id.startb1);
startbut1.setOnClickListener(this);
spiel = new Spiellogik();
}
public View getTheView(){
return myView;
}
public void onClick(View v) {
int id = v.getId();
if (id == R.id.antwort1)
spiel.auswerten(1, this); // spielAuswerten(1);
else if (id == R.id.antwort2)
spiel.auswerten(2, this); // spielAuswerten(2);
else if (id == R.id.antwort3)
spiel.auswerten(3, this); // spielAuswerten(3);
else if (id == R.id.antwort4)
spiel.auswerten(4, this); // spielAuswerten(4);
else if (id == R.id.startb1)
aufrufen();
else if (id==R.id.hauptmeldung)
Toast.makeText(this, "Leider nichts gewonnen. :-(", Toast.LENGTH_LONG).show();
}
View v;
#Override
public void onBackPressed() {
if(this.findViewById(id.mainlay)==getTheView()){
backButtonHandler();
}
else{
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(), QuizActivity.class);
startActivity(intent);
finish();
}
}
public void backButtonHandler() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
QuizActivity.this);
alertDialog.setTitle("Beenden");
alertDialog.setMessage("Sicher Beenden?");
alertDialog.setPositiveButton("Ja",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton("Nein",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void aufrufen(){
setContentView(R.layout.quiz_layout);
for (int n = 1; n <= 4; n++) {
Button btn = null;
switch (n) {
case 1:
btn = (Button) this.findViewById(R.id.antwort1);
btn.setOnClickListener(this);
break;
case 2:
btn = (Button) this.findViewById(R.id.antwort2);
btn.setOnClickListener(this);
break;
case 3:
btn = (Button) this.findViewById(R.id.antwort3);
btn.setOnClickListener(this);
break;
case 4:
btn = (Button) this.findViewById(R.id.antwort4);
btn.setOnClickListener(this);
break;
}
}
spiel.fragen[spiel.aktFrage].anzeigen(this);
}
}
Frage:
package at.lorenzdirry.philosophenquiz;
import at.lorenzdirry.philosophenquiz.R.id;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
class Frage {
private String frage;
private String frage2;
private String frage3;
private String option1;
private String option2;
private String option3;
private String option4;
private int loesung;
public Frage(String f,String f2,String f3, String o1, String o2, String o3, String o4, int l) {
frage = f;
frage2 = f2;
frage3 = f3;
option1 = o1;
option2 = o2;
option3 = o3;
option4 = o4;
loesung = l;
}
public void anzeigen(Activity quizActivity) {
((TextView) quizActivity.findViewById(id.frage)).setText("\u2022 "+frage);
((TextView) quizActivity.findViewById(id.frage2)).setText("\u2022 "+frage2);
((TextView) quizActivity.findViewById(id.frage3)).setText("\u2022 "+frage3);
((Button) quizActivity.findViewById(id.antwort1)).setText(option1);
((Button) quizActivity.findViewById(id.antwort2)).setText(option2);
((Button) quizActivity.findViewById(id.antwort3)).setText(option3);
((Button) quizActivity.findViewById(id.antwort4)).setText(option4);
}
public boolean richtig(int ausgewaehlt) {
if (ausgewaehlt == this.loesung)
return true;
else
return false;
}
}
Spiellogik:
package at.lorenzdirry.philosophenquiz;
import at.lorenzdirry.philosophenquiz.R.id;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
class Spiellogik{
final int ANZAHL_FRAGEN = 8;
Frage[] fragen = new Frage[ANZAHL_FRAGEN];
Random r = new Random();
int aktFrage = r.nextInt(ANZAHL_FRAGEN);
int gewinnstufe = 0;
Spiellogik() {
fragen[0] = new Frage("624-546 v.Chr.","Monismus","\"Alles besteht aus Wasser.\"",
"Thales von Milet", "Aristoteles", "Platon", "Immanuel Kant", 1);
fragen[1] = new Frage("\u2248600 v.Chr.","Daoismus","\"Wer andere kennt, ist klug. Wer sich selbst kennt, ist weise.\"",
"Laotse ", "Alkmaion", "Roger Bacon", "Sokrates", 1);
fragen[2] = new Frage("570-495 v.Chr.","a\u00B2+b\u00B2=c\u00B2","\"Vernunft ist unsterblich, alles andere sterblich.\"",
"Pythagoras", "Thomas von Aquin", "Archytas von Tarent", "Platon", 1);
fragen[3] = new Frage("563-483 v.Chr.","Buddhismus","\"Gl\u00fccklich ist, wer sein ich \u00fcberwunden hat.\"",
"Siddharta Gautama (Buddha)", "Anaximenes", "Antiphon aus Athen", "Kleanthes", 1);
fragen[4] = new Frage("551-479 v.Chr.","Konfuzianismus","\"Mache Treue und Aufrichtigkeit zu obersten Prinzipien.\"",
"Konfuzius", "Melissos", "Damaskios", "Panaitios", 1);
fragen[5] = new Frage("535-475 v.Chr.","Monismus","\"Alles flie\u00dft. (panta rhei)\"",
"Heraklit", "Pyrrhon", "Proklos", "Theodoros", 1);
fragen[6] = new Frage("490-420 v.Chr.","Relativismus","\"Der Mensch ist Ma\u00df aller Dinge.\"",
"Protagoras", "Xenokrates", "Zenon von Sidon", "Jamblichos", 1);
fragen[7] = new Frage("460-370 v.Chr.","Atomismus","\"In Wirklichkeit gibt es nur die Atome und das Leere.\"",
"Leukipp", "Epicharmos", "Thales von Milet", "Philolaos", 1);
}
void auswerten(int schalter, Activity quizActivity) {
if (!fragen[aktFrage].richtig(schalter)) { // falsch beantwortet
if (gewinnstufe == 0) {
Toast.makeText(quizActivity, "Leider nichts gewonnen. :-(", Toast.LENGTH_LONG).show();
}
else {
String str = "Sie haben Gewinnstufe " + gewinnstufe + " erreicht! :-) - Glckwunsch!!!";
Toast.makeText(quizActivity, str, Toast.LENGTH_LONG).show();
}
// Schalter deaktivieren
((Button) quizActivity.findViewById(id.antwort1)).setEnabled(false);
((Button) quizActivity.findViewById(id.antwort2)).setEnabled(false);
((Button) quizActivity.findViewById(id.antwort3)).setEnabled(false);
((Button) quizActivity.findViewById(id.antwort4)).setEnabled(false);
} else {
aktFrage= r.nextInt(ANZAHL_FRAGEN);
if (gewinnstufe < 7) {
fragen[aktFrage].anzeigen(quizActivity);
gewinnstufe++;
((TextView) quizActivity.findViewById(id.richtigeFragen)).setText("Richtig beantwortete Fragen : "+gewinnstufe+"/8");
((ProgressBar) quizActivity.findViewById(id.progressBar1)).setProgress(gewinnstufe);
}
else {
gewinnstufe++;
((TextView) quizActivity.findViewById(id.richtigeFragen)).setText("Richtig beantwortete Fragen : " + gewinnstufe + "/8");
((ProgressBar) quizActivity.findViewById(id.progressBar1)).setProgress(gewinnstufe);
quizActivity.setContentView(R.layout.abschluss_layout);
}
}
}
}
I hope you can help me, pls :)
To return on your Menu activity by using a Button :
Button yourbutton = (Button)findViewById(R.id.yourbutton);
yourbutton.setOnClickListener(new OnClickLIstener(){
#Override
public void onClick(View v){
startActivity(new Intent(this,Menu.class));
}
}
Replace all the vars by yours ;)
I'm trying to convert Activity to a fragment and can't override this methods : onCreateOptionsMenu,onOptionsItemSelected,onContextItemSelected.
,maybe some import statements are missing ? don't know what to do.Her is my Class file :
package com.wts.ui;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainFragment extends Fragment {
protected final static int REQUEST_CODE = 1;
public static WordsDBAdapter dbAdapter;
private CustomAdapter cDataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
// context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
private final static int IDM_INFO = 103;
// options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
private static final int IDM_SETTINGS = 203;
private static final int IDM_QUESTION = 204;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbAdapter = new WordsDBAdapter(getActivity());
dbAdapter.open();
displayListView();
registerForContextMenu(listView);
// ================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor) listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(WordsDBAdapter.ID_COL);
return false;
}
});
// ================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if (word.length() > 0 && translate.length() >= 0) {
Cursor cursor = dbAdapter.fetchWordsByName(word);// chek is
// word
// repeat
if (cursor.moveToFirst()) {
Toast.makeText(getActivity().getApplicationContext(),
getResources().getString(R.string.word_exist),
Toast.LENGTH_SHORT).show();
} else if (!CheckWordInput(word)
|| !CheckTranslateInput(translate)) {
Toast.makeText(
getActivity().getApplicationContext(),
getResources().getString(
R.string.incorrect_input),
Toast.LENGTH_SHORT).show();
} else {
dbAdapter.insertWord(word, translate, " ",
String.valueOf(false), 0, 0, new Date());
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
button = (Button) view.findViewById(R.id.buttonAddWord);
listView = (ListView) view.findViewById(R.id.listWords);
editWord = (EditText) view.findViewById(R.id.editWord);
editTranslate = (EditText) view.findViewById(R.id.editTranslate);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// setContentView(R.layout.activity_main);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_EDIT]);
menu.add(Menu.NONE, IDM_INFO, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_INFO]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_DELETE]);
}
}
//
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT: {
Intent intent = new Intent(getActivity(), EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(WordsDBAdapter.WORD_COL));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(WordsDBAdapter.TRANS_COL));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(WordsDBAdapter.DESC_COL));
startActivityForResult(intent, REQUEST_CODE);
}
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
case IDM_INFO: {
Intent intent = new Intent(getActivity(), InformationActivity.class);
for (int i = 1; i <= InformationActivity.nListItems; i++)
intent.putExtra(String.valueOf(i), cursor.getString(i));
startActivity(intent);
}
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
private void displayListView() {
// Cursor cursor = dbAdapter.fetchAllTranslated();
Cursor cursor = dbAdapter.fetchAllTranslated();
String[] columns = new String[] { WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION, WordsDBAdapter.KEY_SUCCEEDED, };
int[] to = new int[] { R.id.textViewTranslate, R.id.textViewWord,
R.id.textViewSuccessPoints };
cDataAdapter = new CustomAdapter(getActivity(), R.layout.word_info,
cursor, columns, to);
listView.setAdapter(cDataAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_ABOUT: {
Intent intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT: {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
break;
}
case IDM_SETTINGS: {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
break;
}
case IDM_QUESTION: {
if (!StartActivity.isMainActivitySart)
getActivity().onBackPressed();
else {
Intent intent = new Intent(getActivity(),
QuestionActivity.class);
startActivity(intent);
}
}
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (intent.hasExtra(getResources().getString(R.string.fstRow))) {
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(
getResources().getString(R.string.fstRow)),
intent.getExtras().getString(
getResources().getString(R.string.scndRow)),
intent.getExtras().getString(
getResources().getString(R.string.thrdRow)),
null, null, null, null);
displayListView();
}
}
}
#Override
public void onResume() {
super.onResume();
SettingsManager.setPreferedLanguage(getActivity());// set language
displayListView();
}
public static boolean CheckTranslateInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{0,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
public static boolean CheckWordInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{1,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
#Override
public void onDetach() {
super.onDetach();
dbAdapter.close();
}
}
You have to think about what you want your Fragment to be - Fragment or SherlockFragment?
You import this:
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
And so, your overrides aren't overrides because Menu & friends are different classes right now than what Fragment needs - they are ActionBarSherlock's classes.
If you extend SherlockFragment instead, your overrides should work, and it is recommended to extend SherlockFragment if you are using ActionBarSherlock (which based on your tags, you are).
If you want to keep this as a regular fragment, then import:
android.view.Menu
android.view.MenuItem
android.view.MenuInflater
I am trying to update my existing Android Application to work on both mobile phone and Tablet. So I want to change the Activity class to fragment. The below is my activity class.
Individual Activity class
package FXPAL.Unity.Android;
import FXPAL.Unity.Android.Person.CalendarEntry;
import FXPAL.Unity.Android.Person.IM;
import FXPAL.Unity.Android.Person.Person;
import FXPAL.Unity.Android.Person.Status;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class IndividualViewActivity extends Activity {
private static final String DB_TAG = "IndividualView";
//private static final String DB_TAG_PING = "ShowPingView";
private TextView displayName, presence, phoneNum, cellNum, emailAddr, btLocation, calInfo, status;
private ImageView userImage;
private Person personToDisplay;
private String phoneNumber, cellNumber, username, emailAddress;
private TableRow fxpalIMrow, skypeIMrow, msLiveIMrow, gtalkIMrow;
private TableLayout imTable;
private TextView fxpalIMstatus, skypeIMstatus, msLiveIMstatus, gtalkIMstatus, pingText;
private Button nudgeButton, pingButton, clearPingButton, calendarButton;
private LinearLayout pingLayout, pingNudgeButtonLayout;
protected String numToCall, numtype;
private DatabaseHelper db;
//private int pingID = -1;
private UnityMobileApp appCtx;
private static final int DIALOG_CALL_OFFICE_ID = 0;
private static final int DIALOG_CALL_CELL_ID = 1;
protected static final int DIALOG_VIEW_CALENDAR = 2;
private static final int REFRESH_MENU_ID = 0;
protected static final String OFFICE = "office";
private static final String CELL = "cell";
protected static final int MESSAGE_CONNECTION_ERROR_TOAST = 0;
//private static final String DEBUG_TAG = "unity.IndividualViewActivity";
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_CONNECTION_ERROR_TOAST:
Toast.makeText(IndividualViewActivity.this, Consts.CONNECTION_ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
break;
}
}
};
private SharedPreferences prefs;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//doBindService();
setContentView(R.layout.individual_view);
db = new DatabaseHelper(this);
appCtx = (UnityMobileApp) getApplication();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Setup View
displayName = (TextView)findViewById(R.id.individualName);
presence = (TextView)findViewById(R.id.individualPresence);
userImage = (ImageView)findViewById(R.id.individualUserImage);
phoneNum = (TextView)findViewById(R.id.individualPhone);
cellNum = (TextView)findViewById(R.id.individualCellPhone);
emailAddr = (TextView)findViewById(R.id.individualEmail);
btLocation = (TextView)findViewById(R.id.individualLocation);
calInfo = (TextView)findViewById(R.id.individualCalendarInfo);
status = (TextView)findViewById(R.id.individualStatus);
fxpalIMrow = (TableRow)findViewById(R.id.im_fxpal);
skypeIMrow = (TableRow)findViewById(R.id.im_skype);
msLiveIMrow = (TableRow)findViewById(R.id.im_ms_live);
gtalkIMrow = (TableRow)findViewById(R.id.im_gtalk);
fxpalIMstatus = (TextView)findViewById(R.id.im_status_fxpal);
skypeIMstatus = (TextView)findViewById(R.id.im_status_skype);
msLiveIMstatus = (TextView)findViewById(R.id.im_status_ms_live);
gtalkIMstatus = (TextView)findViewById(R.id.im_status_gtalk);
imTable = (TableLayout)findViewById(R.id.individualIMStatus);
nudgeButton = (Button)findViewById(R.id.individual_nudge_button);
pingButton = (Button) findViewById(R.id.individual_ping_button);
calendarButton = (Button)findViewById(R.id.individualViewCalendarButton);
pingText = (TextView)findViewById(R.id.individualPingText);;
clearPingButton = (Button) findViewById(R.id.individualClearPingButton);
pingLayout = (LinearLayout)findViewById(R.id.individualPingInfo);
pingNudgeButtonLayout = (LinearLayout)findViewById(R.id.individual_nudge_ping_layout);
calendarButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(DIALOG_VIEW_CALENDAR);
db.viewEvent(DB_TAG + ":CalendarDialog", username);
}
});
nudgeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(IndividualViewActivity.this, SendNudgeActivity.class)
.putExtra(Consts.EXTRA_USERNAME, personToDisplay.getUsername())
.putExtra(Consts.EXTRA_DISPLAY_NAME, personToDisplay.getDisplayName()));
}
});
pingButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(IndividualViewActivity.this, SendPingActivity.class)
.putExtra(Consts.EXTRA_USERNAME, personToDisplay.getUsername())
.putExtra(Consts.EXTRA_DISPLAY_NAME, personToDisplay.getDisplayName()));
}
});
}
public void onPause(){
super.onPause();
}
public void onDestroy(){
super.onDestroy();
//doUnbindService();
db.close();
}
public void onResume(){
super.onResume();
Intent mIntent = getIntent();
username = mIntent.getStringExtra(Consts.EXTRA_USERNAME);
if(username.equalsIgnoreCase(prefs.getString(Consts.PREF_USERNAME, "")))
pingNudgeButtonLayout.setVisibility(View.GONE);
else
pingNudgeButtonLayout.setVisibility(View.VISIBLE);
personToDisplay = appCtx.getEveryone().get(username);
updateView();
updateInfo();
if (personToDisplay == null || personToDisplay.getCalendar() == null ||
personToDisplay.getCalendar().getCalendar().size() == 0)
calendarButton.setEnabled(false);
else
calendarButton.setEnabled(true);
db.viewEvent(DB_TAG, username);
pingLayout.setVisibility(View.GONE);
//}
}
private void updateInfo(){
ServerHelper.RequestListener listener = new ServerHelper.RequestListener() {
public void onCompleted(ServerHelper.Request request) {
if (request.isUnauthorized())
startActivity(new Intent(IndividualViewActivity.this, LoginActivity.class));
else if (request.isSuccess()) {
Person.PersonHelper.getEveryoneAsync(IndividualViewActivity.this, appCtx.everyone, null, request.getResponseString(),
new Runnable() {
public void run () {
personToDisplay = appCtx.everyone.get(username);
updateView();
}
});
}
}
};
ServerHelper.appCtx = appCtx;
ServerHelper.getStatus (prefs, listener);
}
private void updateView(){
if (personToDisplay == null)
return;
displayName.setText(personToDisplay.getDisplayName());
presence.setText(personToDisplay.getPresenceState());
Status mStatus = personToDisplay.getStatus();
if( mStatus!= null && mStatus.toString().length()>0){
status.setVisibility(View.VISIBLE);
status.setText(mStatus.toString());
}
userImage.setImageBitmap(personToDisplay.getRoundedImage(Consts.LARGE_USER_IMAGE_SIZE, Consts.LARGE_USER_IMAGE_BORDER));
phoneNumber = personToDisplay.getPhoneNum();
if(phoneNumber.length()>0){
phoneNum.setText(OFFICE + ": " + phoneNumber);
phoneNum.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
numToCall = phoneNumber;
numtype = OFFICE;
showDialog(DIALOG_CALL_OFFICE_ID);
}
});}
else
phoneNum.setVisibility(View.GONE);
cellNumber = personToDisplay.getCellPhoneNum();
if(cellNumber.length()>0){
cellNum.setText(CELL + ": " + cellNumber);
cellNum.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
numToCall = cellNumber;
numtype = CELL;
showDialog(DIALOG_CALL_CELL_ID);
}
});}
else
cellNum.setVisibility(View.GONE);
emailAddress = personToDisplay.getEmailAddress();
emailAddr.setText(emailAddress);
emailAddr.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
db.communicate(DB_TAG, "email", username);
Intent emailIntent = new Intent();
emailIntent.setAction(android.content.Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:" + emailAddress));
startActivity(Intent.createChooser(emailIntent, "Select Email Client"));
}
});
if(personToDisplay.hasLocation()){
btLocation.setVisibility(View.VISIBLE);
btLocation.setText(personToDisplay.getLocation().toString());
}
CalendarEntry usefulCalInfo = personToDisplay.getCalendar().getMostUseful();
if(usefulCalInfo != null){
calInfo.setVisibility(View.VISIBLE);
calInfo.setText("Calendar: " + usefulCalInfo.toString());
}
if(personToDisplay.hasIM()){
imTable.setVisibility(View.VISIBLE);
}
for(IM mIM : personToDisplay.getIMList().values()){
switch(mIM.getId()){
case(IM.FXPAL_ID):
fxpalIMrow.setVisibility(View.VISIBLE);
fxpalIMstatus.setText(mIM.getStatus());
break;
case(IM.SKYPE_ID):
skypeIMrow.setVisibility(View.VISIBLE);
skypeIMstatus.setText(mIM.getStatus());
break;
case(IM.MS_LIVE_ID):
msLiveIMrow.setVisibility(View.VISIBLE);
msLiveIMstatus.setText(mIM.getStatus());
break;
case(IM.GTALK_ID):
gtalkIMrow.setVisibility(View.VISIBLE);
gtalkIMstatus.setText(mIM.getStatus());
break;
default:
}
}
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch(id) {
case DIALOG_CALL_OFFICE_ID:
case DIALOG_CALL_CELL_ID:
dialog = CommDialog.getCallDialog(displayName.getText().toString(), numToCall, numtype, IndividualViewActivity.this, db);
break;
case DIALOG_VIEW_CALENDAR:
return CalendarListDialog.getDialog(username, IndividualViewActivity.this, appCtx);
default:
dialog = null;
}
return dialog;
}
public boolean onCreateOptionsMenu(Menu menu){
menu.add(Menu.NONE, REFRESH_MENU_ID, Menu.NONE, "Refresh")
.setIcon(R.drawable.ic_menu_refresh)
.setAlphabeticShortcut('r');
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case REFRESH_MENU_ID:
refresh();
break;
}
return (super.onOptionsItemSelected(item));
}
void refresh() {
// update the location and report it to the server
ReportingService.startLocationRequest(appCtx, true);
// this may still retrieve the old location
updateInfo();
}
}
Please help me guys. I am stuck with this problem since long time.
Regards,
Rakesh