Passing ResourceId as an Integer between Activities - java

I have passed a ResourceId as an integer from my CreateActivity to my MainActivity with the use of putInt(); I would like to be able to pass a drawable from one activity to another.
What should I be looking to do to reference that ResourceId to get the drawable associated with it? or should I look at converting the image to a bitmap, and passing it that way?
LOGCAT
03-19 11:59:41.353: E/AndroidRuntime(5566): FATAL EXCEPTION: main
03-19 11:59:41.353: E/AndroidRuntime(5566): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { cmp=com.example.datetracker/.MainActivity (has extras) }} to activity {com.example.datetracker/com.example.datetracker.MainActivity}: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x12/d=0x0 a=3 r=0x7f090006}
MAINACTIVITY
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;
boolean _isBack = true;
ImageButton add;
String title;
String date;
String time;
int resId;
static final int PICK_CONTACT_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
// retrieving resId, creating drawable
// resId = b.getInt("DRAWABLE");
//Log.e("RESIDRESIED", "DRAWABLE " + resId);
Drawable img = getResources().getDrawable(R.id.btn_picture);
/////
Log.e("TITLE", title);
Log.e("TIME", time);
Log.e("DATE", date);
Event newEvent = new Event();
newEvent.set_date(date);
newEvent.set_title(title);
newEvent.set_time(time);
// set drawable
newEvent.set_drawable(img);
lstEvents.add(newEvent);
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
}
}
}
}
CREATEACTIVITY
public class CreateActivity extends Activity implements OnClickListener {
EditText etTitle;
Button btDate;
Button btTime;
Button btPic;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//onclicklistener
findViewById(R.id.btn_confirm).setOnClickListener(this);
findViewById(R.id.btn_back).setOnClickListener(this);
etTitle = (EditText) findViewById(R.id.editTextTitle);
btDate = (Button) findViewById(R.id.btn_date);
btTime = (Button) findViewById(R.id.btn_time);
btPic = (Button) findViewById(R.id.btn_picture);
}
// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_confirm:
String title = etTitle.getText().toString();
String time = btTime.getText().toString();
String date = btDate.getText().toString();
//int resId = getResources().getInteger(R.id.btn_picture);
int resId = R.id.btn_picture;
Log.e("LOG", title);
Log.e("LOG", time);
Log.e("LOG", date);
Bundle newBundle = new Bundle();
newBundle.putString("TITLE", title);
newBundle.putString("TIME", time);
newBundle.putString("DATE", date);
//Trying to pass a drawable from one activity to another
newBundle.putInt("DRAWABLE", resId);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtras(newBundle);
setResult(RESULT_OK, intent);
finish();
break;
case R.id.btn_back:
finish();
break;
}
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getFragmentManager(), "timePicker");
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
public void showPicturePickerDialog(View v) {
DialogFragment newFragment = new PicturePickerFragment();
newFragment.show(getFragmentManager(), "picturePicker");
}
}

Drawable img = getResources().getDrawable(R.id.btn_picture);
This is wrong.
Drawables are accessed with R.drawable.xyz, R.id.xyz is for layout IDs.
And a resourceID is just an int, so just pass the int from one activity to the other.

Related

Reloading RecyclerView doesn’t update items

I am using the following code:
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
The activity contains a recycler view, I want the activity to reload when I click on refresh but the Recyclerview doesn't fill again, it has the same information than before reloading. If I go to another activity and come back to this one, then it does change.
What I am doing wrong?
Here is the complete activity code:
public class SyncActivity extends Activity {
private static String TAG = "SynActivity";
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private TextView textView;
private ImageView backArrow;
private ImageView refresh;
// Sesión actual
private Usuario usuario;
private String sessionid;
List<TrafficSign> tsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync);
tsList = new ArrayList<TrafficSign>();
// Sesión actual
sessionid = getIntent().getExtras().getString("sessionid");
usuario = (Usuario) getIntent().getExtras().get("usuario");
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
textView = (TextView) findViewById(R.id.texto);
backArrow = (ImageView) findViewById(R.id.backarrow);
refresh = (ImageView) findViewById(R.id.refresh);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// specify an adapter with the list to show
ConexionSQLiteHelper conexionSQLiteHelper = new ConexionSQLiteHelper(this, NOMBRE_BD, null, 1);
SQLiteDatabase dbread = conexionSQLiteHelper.getReadableDatabase();
Cursor c = dbread.rawQuery(COMRPUEBA_SYNC, new String[]{usuario.getUsername()});
// Si hay conexión a internet y hay datos en SQLite, sincronizamos.
if (c.getCount() > 0) {
textView.setVisibility(View.INVISIBLE);
if (c.moveToFirst()) {
while (!c.isAfterLast()) {
tsList.add(new TrafficSign(c.getDouble(c.getColumnIndex(CAMPO_LONGITUD)),
c.getDouble(c.getColumnIndex(CAMPO_LATITUD)),
c.getDouble(c.getColumnIndex(CAMPO_ANCHO)),
c.getDouble(c.getColumnIndex(CAMPO_ALTO)),
c.getString(c.getColumnIndex(CAMPO_CLASE)),
c.getString(c.getColumnIndex(CAMPO_USERNAME))));
c.moveToNext();
}
}
c.close();
dbread.close();
mAdapter = new SyncAdapter(tsList);
mRecyclerView.setAdapter(mAdapter);
}else{
textView.setVisibility(View.VISIBLE);
}
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncActivity.this, MainActivity.class);
intent.putExtra("sessionid", sessionid);
intent.putExtra("usuario", usuario);
startActivity(intent);
}
});
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
});
}
}
You can Simply use
finish();
startActivity(getIntent());
to refresh an Activity from within itself.

Keep the data save in sharedPreference although pressed back button - Android Studio

I have some problem as I mention in my question. I have two activity, Activity A and Activity B. When I Enter some data in Activity A, then I press next button, it will redirect to Activity B. At Activity B, I also enter some data. When I press back button, the data at Activity A is display as I entered before. When I press next button, the data that I entered at Activity B is missing. Below is my SharedPreferences code.
Activity A:
public class NewSuggestion extends AppCompatActivity {
private EditText etYear, etMonth, etTitle, etOwnValue;
private RadioGroup rgSuggestWill;
private RadioButton radioButton;
private Button btnNext;
ArrayAdapter<CharSequence> adapter;
private Spinner spReviewer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etTitle = findViewById(R.id.etTitle);
etYear = findViewById(R.id.etYear);
etMonth = findViewById(R.id.etMonth);
rgSuggestWill =findViewById(R.id.rgSuggestWill);
final Calendar c = Calendar.getInstance();
String mm = c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.US);
int yy = c.get(Calendar.YEAR);
etYear.setText(new StringBuilder().append(yy));
etMonth.setText(new StringBuilder().append(mm));
spReviewer = findViewById(R.id.spReviewer);
adapter = ArrayAdapter.createFromResource(this,R.array.reviewer,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spReviewer.setAdapter(adapter);
spReviewer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("title",etTitle.getText().toString());
editor.putString("year",etYear.getText().toString());
editor.putString("month",etMonth.getText().toString());
// get selected radio button from radioGroup
int selectedId = rgSuggestWill.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = findViewById(selectedId);
editor.putString("suggestionwill",radioButton.getText().toString());
if (spReviewer.getSelectedItem().toString().equals("Please choose")){
AlertDialog alertDialog = new AlertDialog.Builder(NewSuggestion.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Please choose your reviewer");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}else{
editor.putString("reviewer",spReviewer.getSelectedItem().toString());
Intent intent = new Intent(NewSuggestion.this,NewSuggestion2.class);
startActivity(intent);
}
editor.apply();
}
});
}
#Override
public void onBackPressed() {
Intent intent = new Intent(NewSuggestion.this, DashboardApp.class);
startActivity(intent);
}
}
Activity B:
public class NewSuggestion2 extends AppCompatActivity {
private EditText etPresent, etDetails, etBenefit;
private ImageView imgAttach,btnCamera,btnGallery;
private Button btnNext,btnClear;
private Intent intent;
private Bitmap bitmap;
private int REQUEST_CODE = 1;
public static final int RequestPermissionCode = 1 ;
public static final String DEFAULT = "N/A";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_suggestion2);
final ActionBar abar = getSupportActionBar();
View viewActionBar = getLayoutInflater().inflate(R.layout.activity_new_suggestion, null);
ActionBar.LayoutParams params = new ActionBar.LayoutParams(//Center the textview in the ActionBar !
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.MATCH_PARENT,
Gravity.CENTER);
TextView tvTitle = viewActionBar.findViewById(R.id.title);
tvTitle.setText("NEW SUGGESTION (Cont..)");
abar.setCustomView(viewActionBar, params);
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
//abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
imgAttach = findViewById(R.id.imgAttach);
btnCamera=findViewById(R.id.btnCamera);
EnableRuntimePermission();
btnCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 7);
}
});
btnGallery=findViewById(R.id.btnGallery);
btnGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Photo"),REQUEST_CODE);
}
});
btnNext = findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
Intent intent = new Intent(NewSuggestion2.this,ConfirmSuggestion.class);
startActivity(intent);
}
});
btnClear = findViewById(R.id.btnClear);
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgAttach.setImageBitmap(null);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 7 && resultCode == RESULT_OK) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imgAttach.setImageBitmap(bitmap);
}
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data != null && data.getData() != null){
Uri uri = data.getData();
try{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imgAttach.setImageBitmap(bitmap);
}catch (IOException e){
e.printStackTrace();
}
}
}
public void EnableRuntimePermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(NewSuggestion2.this,
Manifest.permission.CAMERA))
{
Toast.makeText(NewSuggestion2.this,"CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(NewSuggestion2.this,new String[]{
Manifest.permission.CAMERA}, RequestPermissionCode);
}
}
#Override
public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
switch (RC) {
case RequestPermissionCode:
if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(NewSuggestion2.this,"Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(NewSuggestion2.this,"Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
}
break;
}
}
#Override
public void onBackPressed() {
}
}
Assign value to present,details,benefit from sharedpref
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
etPresent = findViewById(R.id.etPresent);
etDetails = findViewById(R.id.etDetails);
etBenefit = findViewById(R.id.etBenefit);
etPresent.setText(sharedPref.getString("present", ""));
etDetails.setText(sharedPref.getString("details", ""));
etBenefit.setText(sharedPref.getString("benefit", ""));
In Activity B make sure you save data in onBackPressed()
#Override
public void onBackPressed() {
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.apply();
super.onBackPressed();
}
You have to override the onBackPress() method.In Activity B it is necessary to put data in to SharedPreferences.
#Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("present", etPresent.getText().toString());
editor.putString("details", etDetails.getText().toString());
editor.putString("benefit", etBenefit.getText().toString());
editor.commit();
}

is not an enclosing class / new Intent Cannot Resolve Constructor

Thanks for checking out my question!
I have a relativly ismple loop which will add a onClickListener to each ImageView I add to my Layout, however when trying to add a new Intent to it, it gives me one of the following errors:
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
Will result in the "Cannot resolve Constructor 'Intent ...." error.
So when I was looking for a solution, people suggested to change "this" to "MainActivity.this", but...
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
resulted into: com.myName.appName.MainActivity is not an enclosing class
Here is the ImageActivity class:
public class ImageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image);
String URL = getIntent().getExtras().getString("URL");
ImageView imageView = (ImageView) findViewById(R.id.image);
imageView.getLayoutParams().height = (int) (imageView.getLayoutParams().width * (Float.valueOf(String.valueOf(1.41))));
Picasso.with(this).load(URL).into(imageView);
}
The weird thing is that I have done numerous new Intent's during my play time with creating apps, but I cant seem to solve this one. What am I missing here?
FULL CODE FROM HERE
public class DetailsActivity extends AppCompatActivity {
TextView TVWeChatIdValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
String dataString = getIntent().getExtras().getString("dataString");
String[] itemData = dataString.split(",");
String category = itemData[0];
Log.e("DetailsActivity", category);
String itemID = itemData[1];
Log.e("DetailsActivity", itemID);
String imageURLsString = itemData[2];
Log.e("DetailsActivity", imageURLsString);
String description = itemData[3];
Log.e("DetailsActivity", description);
String price = itemData[4];
Log.e("DetailsActivity", price);
String itemCode = category + itemID;
TextView textView;
textView = (TextView) findViewById(R.id.Title);
textView.setText(getResources().getString(R.string.app_name));
textView = (TextView) findViewById(R.id.ItemReferralValue);
textView.setText(itemCode);
textView = (TextView) findViewById(R.id.ItemPriceValue);
textView.setText(price);
TVWeChatIdValue = (TextView) findViewById(R.id.WeChatIDValue);
new DatabaseTask(this, "details", "GETWECHATID").execute();
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ItemDetailsContent);
String[] imageURLs = imageURLsString.split("/");
for (int i = 0; i < imageURLs.length; i++){
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(182),getPx(256)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
final String imageURL = ".../images/" + imageURLs[i];
Picasso.with(this).load(imageURL).into(image);
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
linearLayout.addView(image);
}
ImageView imageView = (ImageView) findViewById(R.id.ItemDetailsDescription);
String imageURL = ".../images/" + description;
Picasso.with(this).load(imageURL).into(imageView);
}
public void SetWeChatId(String mValue) {
TVWeChatIdValue.setText(mValue);
}
public int getPx(int dimensionDp) {
float density = getResources().getDisplayMetrics().density;
return (int) (dimensionDp * density + 0.5f);
}
}
WORKING CODE
public class MainActivity extends AppCompatActivity {
TextView TVWeChatIdValue;
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView;
textView = (TextView) findViewById(R.id.Title);
textView.setText(getResources().getString(R.string.app_name));
textView = (TextView) findViewById(R.id.SubTitle);
textView.setText(getResources().getString(R.string.slogan));
textView = (TextView) findViewById(R.id.MoreForWomen);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("women");
}
});
textView = (TextView) findViewById(R.id.MoreForMen);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("men");
}
});
textView = (TextView) findViewById(R.id.MoreForKids);
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
OpenCatalog("kids");
}
});
}
public void GetData() {
TVWeChatIdValue = (TextView) findViewById(R.id.WeChatIDValue);
new DatabaseTask(this, "main", "GETWECHATID").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForWomenContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "WOMEN", "GETNEWESTITEMS").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForMenContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "MEN", "GETNEWESTITEMS").execute();
linearLayout = (LinearLayout) findViewById(R.id.NewItemsForKidsContent);
linearLayout.removeAllViewsInLayout();
new DatabaseTask(this, linearLayout, "KIDS", "GETNEWESTITEMS").execute();
}
public void SetWeChatId(String mValue) {
TVWeChatIdValue.setText(mValue);
}
public void ProcessNewItems(LinearLayout mLinearLayout, final String mCategory, final HashMap<Integer, Item> mItems){
for (int i = 0; i < mItems.size(); i++) {
ImageView image = new ImageView(this);
image.setLayoutParams(new android.view.ViewGroup.LayoutParams(getPx(96),getPx(128)));
image.setPadding(getPx(3),getPx(3),getPx(3),getPx(3));
String imageURL = ".../images/" + mItems.get(i).getImageURLs()[0];
Picasso.with(this).load(imageURL).into(image);
mLinearLayout.addView(image);
final int index = i;
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ShowItemDetails(mCategory, mItems.get(index));
}
});
}
}
void ShowItemDetails(String mCategory, Item mItem){
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("dataString", mItem.GetDataString());
Log.e("CatalogActivity", mItem.GetDataString());
startActivity(intent);
}
void OpenCatalog(String mCategory){
//show catalog
Intent intent = new Intent(this, CatalogActivity.class);
intent.putExtra("category", mCategory);
startActivity(intent);
}
public int getPx(int dimensionDp) {
float density = getResources().getDisplayMetrics().density;
return (int) (dimensionDp * density + 0.5f);
}
#Override
public void onResume() {
super.onResume();
GetData();
}
}
You need to use the name of the Activity subclass which contains the code that creates the OnClickListener. In many examples, this is MainActivity. However, this doesn't seem to be the case in your code. Since you are in a class named DetailsActivity then use that name:
Intent intent = new Intent(DetailsActivity.this, ImageActivity.class);
From what I can see of your code here, I strongly suggest that you learn about ListView and RecyclerView. They are a bit complex, but once you understand them, they do much of the work for you similar to what you are trying to do here. For one thing, they are more efficient than your own code because they only create as many views as are visible.
Let's look more closely at your other example:
public class MainActivity extends AppCompatActivity {
// ...
void ShowItemDetails(String mCategory, Item mItem){
Intent intent = new Intent(this, DetailsActivity.class);
intent.putExtra("dataString", mItem.GetDataString());
startActivity(intent);
}
}
Notice that the ShowItemDetails() is inside the MainActivity class. So this refers to an instance of that class which can be used wherever a Context is needed. (For more details about this you need to read about inheritance and polymorphism.)
On the other hand, your original code creates an Intent in a method which is inside an anonymous subclass of OnClickListener which cannot be used as a Context. However the anonymous inner class is in a method inside DetailsActivity which inherits from Context. In order to access an instance of this outer class, you have to use DetailsActivity.this.
For more details you should learn about the special this reference and inner classes.
You have this block
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
intent = new Intent(MainActivity.this, ImageActivity.class);
intent.putExtra("URL", imageURL);
startActivity(intent);
}
});
Change MainActivity.this to whatever Activity subclass that is setting the OnClickListener. That would be DetailsActivity.this in your case. Basically the enclosing activity just means the name of the class file (which is also the name of the Activity class) in which the Activity is being defined, this Activity encapsulates the call to .setOnClickListener() to which you are passing an anonymous inner class, which is being enclosed inside your DetailsActivity, hence the name enclosing activity. Hope that makes sense

Edit listView value

I have 3 activities, A, B and C.The flow of activity is from A to B then C. From C, all the images and value will be returned to B then A. All the returned value and image will be loaded in listView A.
The listView is clickable and once it is clicked, it will intent to B to do some edition. But the problem now is when I edit the text value in B and return to A, I get a new list instead of updating the old one.
What's wrong here ? Anyone can help?
Activity C
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_fit_screen);
selectImage();
b = (ImageView) findViewById(R.id.imageView3);
t = (EditText) findViewById(R.id.editText38);
cancel=(Button)findViewById(R.id.button15);
ok=(Button)findViewById(R.id.button16);
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
finish();
}
});
ok.setOnClickListener(new View.OnClickListener()
{ // return to B
public void onClick(View arg0)
{
Intent returnIntent=new Intent();
text=t.getText().toString();
b.setDrawingCacheEnabled(true);
b.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
b.layout(0, 0, b.getMeasuredWidth(), b.getMeasuredHeight());
b.buildDrawingCache(true);
returnIntent.putExtra("text", text);
if (b.getDrawingCache() != null) {
Bitmap bitmap = Bitmap.createBitmap(b.getDrawingCache());
if (bitmap == null) {
Log.e("TAG", "getDrawingCache() == null");
}
Global.img = bitmap;
}
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
Activity B
ImageButton imageButton;
ImageView viewImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt = (EditText) findViewById(R.id.editText36);
txt1=(TextView)findViewById(R.id.textView57);
Button b = (Button) findViewById(R.id.button17);
addListenerOnButton();
viewImage = (ImageView) findViewById(R.id.imageView2);
if(getIntent().getExtras()!=null) { //if has value pass from A
final String Amount = getIntent().getExtras().getString("result");
final String description1 = getIntent().getExtras().getString("description");
txt1.setText(description1);
txt.setText(Amount);
}
b.setOnClickListener(new View.OnClickListener() { // return to A
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a = "Project";
text = txt.getText().toString(); // amount
returnIntent.putExtra("text", text);
returnIntent.putExtra("a", a);
returnIntent.putExtra("c", c);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img);
}
public void addListenerOnButton() {
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Global.img=null;
Intent i = new Intent(B.this,C.class);
startActivityForResult(i, PROJECT_REQUEST_CODE);
}
});
}
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
if(requestCode==PROJECT_REQUEST_CODE) { // receive fom C
if(data!=null&&data.hasExtra("text")) {
c = data.getStringExtra("text");
txt1.setText(c);
viewImage.setImageBitmap(Global.img); // image from C can be shown here
}
}
else if (requestCode==CAMERA_REQUEST_CODE)
{
}
}
}
Activity A
public class Claims1 extends Fragment {
ListView listV;
String description;
String result="";
String name;
long as=0;
TextView c;
ImageView v;
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
String Text;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
setHasOptionsMenu(true);
View claims = inflater.inflate(R.layout.receipt_text, container, false);
v=(ImageView)claims.findViewById(R.id.imageView4);
listV = (ListView) claims.findViewById(R.id.listView1);
android.support.v7.app.ActionBar myActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
myActionBar.setHomeButtonEnabled(true);
ImageView imageView = new ImageView(myActionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
adapter=new ArrayAdapter<String>(getActivity(),R.layout.claims,R.id.textView1,m_listItems);
android.support.v7.app.ActionBar.LayoutParams layoutParams = new android.support.v7.app.ActionBar.LayoutParams(
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.support.v7.app.ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL); // for icon in action bar
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
myActionBar.setCustomView(imageView);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
if(name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), B.class);
intent.putExtra("bitmap",true);
intent.putExtra("name",name);
intent.putExtra("result",result);
startActivityForResult(intent,0);
}
}
});
return claims;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.my_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create1:
AlertDialogRadio();
return true;
}
return (super.onOptionsItemSelected(item));
}
public void AlertDialogRadio() {
final CharSequence[] ClaimsModel = {"B", "Petrol"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Class");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(),B.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
m_listItems.add(Text);
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
if (Global.img != null) {
v.setImageBitmap(Global.img);
}
as = Long.parseLong(result);
c.setText(" " + name + "------" + "RM " + result);
break;
}
}
Edited
Add a global variable in A - private int mClickedPosition;
Add mClickedPosition = position; in OnItemClick
then
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
m_listItems.set(mClickedPosition,Text);
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
11-16 18:15:54.751 23044-23044/com.example.project.project
E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 23044
java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=0, result=-1, data=Intent {
(has extras) }} to activity
{com.example.project.project/com.example.project.project.MainActivity}:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at android.app.ActivityThread.deliverResults(ActivityThread.java:3681)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3724)
m_listItems.set(mClickedPosition,Text);
in your activity A onActivityResult method when you return from activity B after editing you are adding new item into arraylist using this code m_listItems.add(Text);
instead of adding new item you update the array list using this code
m_listItems.set(position Text);
Try edit your code like this:
case 0:
result = data.getStringExtra("text");
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:"+result);
Text=" "+name+" "+"RM"+result+"";
if (m_listItems.size() == 0) {
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition,Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;

Fragment returning null from intent

So i made a bunch of 4 buttons , put an intent to each of them . They all navigate to the same Fragment class . But their extras are different, so if button1 was clicked , Fragment would open and do a certain action , if button2 was clicked , Fragment would do another action and so on. I tried the code on normal activities and it worked , but in fragments its not working . It just returns me "Id is null"
Class sending the intent
public class Intennt extends ActionBarActivity {
Button bt1,bt2,bt3,bt4;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_intennt);
bt1 = (Button) findViewById(R.id.button);
bt2 = (Button) findViewById(R.id.button2);
bt3 = (Button) findViewById(R.id.button3);
bt4 = (Button) findViewById(R.id.button4);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,ItemDetailFragment.ACTION_1);
startActivity(i);
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, ItemListActivity.class);
i.putExtra(ItemDetailFragment.ID_ACTION,
ItemDetailFragment.ACTION_2);
startActivity(i);
}
});
}
Fragment receiving the intent and extras
public class ItemDetailFragment extends Fragment {
public static final int ACTION_1 = 1;
public static final int ACTION_2 = 2;
public static final int ACTION_3 = 3;
public static final int ACTION_4 = 4;
public static final int ACTION_NULL = -1;
public static final String ID_ACTION = "action_id";
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public ItemDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
// Load the dummy content specified by the fragment
// arguments. In a real-world scenario, use a Loader
// to load content from a content provider.
mItem =
DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
int id = getActivity().getIntent().getIntExtra(ID_ACTION, -1);
if (id == ACTION_NULL) {
Log.d("TAG", "id is null");
Toast.makeText(getActivity(), "id is null!",
Toast.LENGTH_SHORT).show();
} else if (id == ACTION_1) {
Log.i("TAG", "ALLOHA! from button 1");
Toast.makeText(getActivity(), "Aloha from button 1!",
Toast.LENGTH_LONG).show();
} else if (id == ACTION_2) {
Log.i("TAG", "Hello from button 2");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_3) {
Log.i("TAG", "Hello from button 3");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
else if (id == ACTION_4) {
Log.i("TAG", "Hello from button 4");
Toast.makeText(getActivity(),"Hello from button 2!",
Toast.LENGTH_LONG).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_item_detail,
container, false);
return rootView;
}
}
To navigate to a fragment, you need to instantiate the fragment class then use the FragmentManager to proceed to a transaction :
FragmentClass fragment = new FragmentClass();
getFragmentManager()
.beginTransaction()
.replace(R.id.your_fragment_view, fragment)
.commit();
You can proceed to every action right in the current activity (as it stays the main activity).
public class Questions extends DialogFragment {
private static Button Submit;
public int count = 0;
public interface DialogListener {
void onQuestionsFinish(ArrayList<xmlQuestion> l);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
//getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Submit = (Button) rootView.findViewById(R.id.SubmitButton);
Submit.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0){
for(int i = 0; i<questionList.size(); i++)
{
questionList.get(i).setAnswer();
}
DialogListener activity = (DialogListener) getActivity();
activity.onQuestionsFinish(questionList);
Questions.this.dismiss();
}
});
DisplayMetrics metrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
yInch = metrics.ydpi;
pixHeight = metrics.heightPixels;
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point(); display.getSize(size);
screenWidth=size.x; screenHeight=size.y;
LinearLayout.LayoutParams bodyParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,screenHeight*900/1024);
BodyLayout.setLayoutParams(bodyParams);
WindowManager.LayoutParams wmlp = getDialog().getWindow().getAttributes();
wmlp.height=screenHeight; wmlp.width=screenWidth;
getDialog().getWindow().setAttributes(wmlp);
WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
lp.dimAmount=0.4f;
getDialog().getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getDialog().setCanceledOnTouchOutside(true);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, android.support.v7.appcompat.R.style.Theme_AppCompat_Light);
}
public Questions()
{
}
}
You don't have to use intents to start fragments. My main benefit for using fragments is being able to reference the data in each one much easier. You can simply create a new instance of your fragment class, and assign it's public variables. Then start it like so...
Questions q = new Questions();
q.count = 0;
q.show(getSupportFragmentManager(), "Dialog Fragment");

Categories

Resources