Why the name in listView keep changing? - java

I have a listView in Activity A as shown below. All the values and name were actually returned from Activity C to B then only A.
When the first list is clicked, it should display text Project and value 3 on editText B. But it displays Medical which was actually getting from the last list.
After I change the value from 3 to 43 and return to A, the name changed. What should I do so that the name will remain the same ?
Activity A
ArrayAdapter<String> adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
int mClickedPosition;
adapter=new ArrayAdapter<String (getActivity(),R.layout.claims,R.id.textView1,m_listItems);
listV = (ListView) claims.findViewById(R.id.listView1);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if list clicked
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
if (name.equals("Project")) {
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true); // image
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}
}
});
return claims;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0: // for Project
result = data.getStringExtra("text"); //get from B
name = data.getStringExtra("a");
description = data.getStringExtra("c");
as = Long.parseLong(result);
Log.d("FIRST", "result:" + result);
Text = " " + name + " " + "RM" + result + "";
if (mClickedPosition == -1) { // if is icon button clicked
m_listItems.add(Text);
} else {
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
case 1: // for Medical
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.clear();
if (mClickedPosition==-1)
{
m_listItems.add(Text);
}
else
{
m_listItems.set(mClickedPosition, Text);
}
adapter.notifyDataSetChanged();
listV.setAdapter(adapter);
break;
Activity B (Project1)
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); // receive from Activity C
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
viewImage.setImageBitmap(Global.img); // receive from C
}
Noted that the result in Activity A represents value 3,5 while name represents project and Medical. How can I fix this ? Please help.

From what I understood, your variable name in Activity A contains previously resulted value (from Activity B) and not from row you have clicked on listview i.e. "Medical" value you previously got from Activity B which held by variable name and on your listview click event you have checks the if name is "Medical" or "Project" (and in this case it is "Medical" and hence Medical activity is started).
One solution is to get the value("Project/Medical") from listview.
Try this code.
Activity A
mClickedPosition = position;
String temp[] = m_listItems.get(position).split("\\s\\s+");
result = temp[temp.length - 1].trim();
result = result.replace("RM","");
name = temp[1].trim();
if (name.equals("Project")) {
Intent intent = new Intent(Claims1.this.getActivity(), Project1.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 0);
Log.e("RESULT", "Result= " + result);
}
else if(name.equals("Medical"))
{
Intent intent = new Intent(Claims1.this.getActivity(), Medical.class);
intent.putExtra("bitmap", true);
intent.putExtra("name", name);
intent.putExtra("result", result);
startActivityForResult(intent, 1);
}

Related

How to access to the specific Folder in Android Studio?

I need to access the specific folder depending on the name of the created project. In Main_Activity the name of this project is filled and new folder is created. Thus, Camera_Activity saves the photos taken in that folder. Next I access Gallery_Activity, but it never goes to the folder of the created project. How can I access to that folder?
An example: Name of the created folder: Proj_1, but user select the photos from another one that opens by default, the uri that comes out is:
content://com.android.externalstorage.documents/document/primary%3APictures%2FCaptures_Camera2%2FProj_aa%2Fpic_040621_110254.jpeg
Part of AndroidManifest.xml
...
<uses-feature android:name="android.hardware.camera2.full" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
...
MainActivity.java
...
createNewProject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Coge el nombre de EditText, crea nueva carpeta y empieza la captura de las imagenes
if(newName.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(), "Please, fill in the field.", Toast.LENGTH_LONG).show();
} else {
name = newName.getText().toString();
GlobalVariables.ProjectName = name;
Intent intent = new Intent(MainActivity.this, Camera_Activity.class);
startActivity(intent);
}
}
});
...
Camera_Activity.java takes the necessary photos, saves them and has a button to enter the gallery:
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mTextureView = findViewById(R.id.camera_preview);
btn_take_pic = findViewById(R.id.button_take_photo);
acceptButton = findViewById(R.id.btn_ok);
cancelButton = findViewById(R.id.btn_cancel);
btn_gallery = findViewById(R.id.go_to_gallery);
imagePreview = findViewById(R.id.image_view_photo_preview);
...
// File name to save the picture
// First is getting the new project name from previous Activity:
String newProjName = GlobalVariables.ProjectName;
// Creating part of the name for image: timestamp. That will be: pic_tamestamp.jpeg
#SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("ddMMyy_HHmmss").format(new Date());
directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Captures_Camera2/Proj_" + newProjName);
GlobalVariables.MyDirectoryPath = directory.getPath();
if (!directory.exists() || !directory.isDirectory())
directory.mkdirs();
mFile = new File(directory, "pic_" + timestamp + ".jpeg");
pathToFile = mFile.getPath();
....
// ------------ GO TO GALLERY ---------
btn_gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "You are going to Gallery...");
Intent GalleryIntent = new Intent(context, Gallery_Activity.class);
startActivity(GalleryIntent);
}
});
// ------------ SAVE PHOTO TO THE GALLERY ---------
acceptButton.setOnClickListener(new View.OnClickListener() {//26
#Override
public void onClick(View v) {
Toast.makeText(context, "Image saved to " + pathToFile, Toast.LENGTH_LONG).show();
// Recreating the activity with a new instance
recreate();
}
});
...
Gallery_Activity.java
public class Gallery_Activity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
private static final String TAG = "GalleryActivity";
private final Context context = this;
private ImageView imageView1, imageView2;
private final int CODE_IMAGE_GALLERY_FIRST = 1;
private final int CODE_IMAGE_GALLERY_SECOND = 2;
private final int CODE_MULTIPLE_IMAGES_GALLERY = 3;
// Variables to check the name
private String directoryPath;
private String MyPath1 = null;
private String MyPath2 = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Keeping the screen on even when there is no touch interaction
final Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_gallery);
imageView1 = findViewById(R.id.imageView1);
// If you make a short click in the ImageView, you can choose only one image, if it is long click, you can choose two images
imageView1.setOnClickListener(this);
imageView1.setOnLongClickListener(this);
imageView2 = findViewById(R.id.imageView2);
imageView2.setOnClickListener(this);
imageView2.setOnLongClickListener(this);
directoryPath = GlobalVariables.MyDirectoryPath;
Log.d(TAG, " The path from Camera_Activity is: " + directoryPath); // /storage/emulated/0/Pictures/Captures_Camera2/Proj_*
chooseMultipleImages();
}
private void chooseMultipleImages() {
// TODO: here it does NOT enter the giving folder although using the path
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting two images.."), CODE_MULTIPLE_IMAGES_GALLERY);
}
....
public void processImages(View view) {
//Toast.makeText(context, "Going to detect features...", Toast.LENGTH_SHORT).show();
Intent processIntent = new Intent(context, ImageProcessing.class);
startActivity(processIntent);
finish();
}
#Override
public boolean onLongClick(View v) {
recreate();
return false;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.imageView1){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting first image.."), CODE_IMAGE_GALLERY_FIRST);
}
else if(v.getId() == R.id.imageView2){
startActivityForResult(Intent.createChooser(new Intent()
.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
.setAction(Intent.ACTION_GET_CONTENT)
.setType("image/*")
,"Selecting second image.."), CODE_IMAGE_GALLERY_SECOND);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ContentResolver resolver = this.getContentResolver();
// Get data from the folder
assert data != null;
Uri MyData = data.getData(); // for simple image
ClipData MultiImg = data.getClipData(); // for multiple images
GlobalVariables.countImg = MultiImg.getItemCount();
/* ******************************************
To pick multiples images from Gallery
******************************************
*/
if (requestCode == CODE_MULTIPLE_IMAGES_GALLERY && resultCode == RESULT_OK ){
/*
// TODO: For multiple images, more than 2 change this
int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
for(int i = 0; i < count; i++)
Uri imageUri = data.getClipData().getItemAt(i).getUri();*/
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
if(GlobalVariables.countImg == 2){
// Getting name of the picture and print it
MyPath1 = MultiImg.getItemAt(0).getUri().toString();
MyPath2 = MultiImg.getItemAt(1).getUri().toString();
String Name1 = StringUtils.right(MyPath1,22);
String Name2 = StringUtils.right(MyPath2,22);
//String Proj_name = StringUtils.
GlobalVariables.PictureName1 = Name1;
GlobalVariables.PictureName2 = Name2;
Log.d(TAG, "--- First data name: " + StringUtils.right(MyPath1,22));
Log.d(TAG, "--- Second data name: " + StringUtils.right(MyPath2,22));
//Log.d(TAG, "Selected Items: " + clipData.getItemCount());
Log.d(TAG, "The full path is: " + MultiImg.getItemAt(0).getUri().toString());
// Showing images in the imageView
imageView1.setImageURI(MultiImg.getItemAt(0).getUri());
imageView2.setImageURI(MultiImg.getItemAt(1).getUri());
} else if (MyData != null ){
Log.d(TAG, "Only one image selected..");
Toast.makeText(context, "You should select 2 images and not only one", Toast.LENGTH_LONG).show();
recreate();
}
// MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
else if (GlobalVariables.countImg > 2){
//Log.d(TAG, "More than two selected images...");
Toast.makeText(context, "You should select 2 images and not ..." + GlobalVariables.countImg, Toast.LENGTH_LONG).show();
recreate();
}
}
/* ******************************************
To pick only one image fom Gallery for
each of ImageView and check that they
are different.
******************************************
*/
// pick image to the imageView1
else if(requestCode == CODE_IMAGE_GALLERY_FIRST && resultCode == RESULT_OK && MyData != null){
MyPath1 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView2 has an image: \n" + StringUtils.right(MyPaths2,22));
assert StringUtils.right(MyPath1, 22) != null;
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName1 = StringUtils.right(MyPath1,22);
imageView1.setImageURI(MyData);
}
}
// pick image to the imageView2
else if(requestCode == CODE_IMAGE_GALLERY_SECOND && resultCode == RESULT_OK && MyData != null) {
MyPath2 = MyData.getPath();
//Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView1 has an image: \n" + StringUtils.right(MyPaths2,22));
if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
}
else{
GlobalVariables.PictureName2 = StringUtils.right(MyPath2,22);
imageView2.setImageURI(MyData);
}
}
}
....
}
Can someone advise me on how I can solve this problem?
It is clear that I could leave things as they are and tell the user to check the folder where he selects the photos. But I would like it to be something more fluid and intuitive.
Thanks in advance.
private ArrayList<File> m_list = new ArrayList<File>();
String folderpath = Environment.getExternalStorageDirectory()
+ File.separator + "folder_name/";
File dir = new File(folderpath);
m_list.clear();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (File file : files) {
if (!file.getPath().contains("Not_Found"))
m_list.add(file);
}
}

null value on variable passed from inside a onclick response

Is there any reason why method CreatePlan won't allow me access to variable recipe_name from the onRecipeClicked function which is retrieved from the recyclerview adapter. The Log shows that the value is retrieved from the recyclerview, but I can't seem to pass it to another method.
Any help is appreciated.
Update
Also is there a way of assigning the auto incremented id created from createPlanRecipe to the id variable in createPlan?
public class CreateMealPlan extends MainActivity {
DatePicker datepicker;
Button submit;
List<com.stu54259.plan2cook.Model.Category> listRecipe = new ArrayList<>();
Cursor c;
RecyclerView recipeList;
RecipeListAdapter adapterRecipe;
String recipe_name;
EditText editPlanName;
Integer id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_meal_plan);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent a = new Intent(CreateMealPlan.this,MainActivity.class);
startActivity(a);
break;
case R.id.recipes:
Intent b = new Intent(CreateMealPlan.this,RecipeSearch.class);
startActivity(b);
break;
/*case R.id.shoppingList:
Intent c = new Intent(CreateMealPlan.this, ShoppingList.class);
startActivity(c);
break;*/
case R.id.mealPlan:
Intent d = new Intent(CreateMealPlan.this, MenuPlan.class);
startActivity(d);
break;
/*case R.id.reminder:
Intent e = new Intent(CreateMealPlan.this, Reminder.class);
startActivity(e);
break*/
}
return false;
}
});
datepicker = findViewById(R.id.calendarView);
ListRecipes();
RecipeListAdapter.OnRecipeClickListener listener = new RecipeListAdapter.OnRecipeClickListener() {
public void onRecipeClicked(int position, String recipe_name) {
Log.d("Recipe selected", recipe_name);
}
};
adapterRecipe = new RecipeListAdapter(this, listRecipe, listener);
recipeList = findViewById(R.id.recipes);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this,
LinearLayoutManager.VERTICAL, false);
recipeList.setLayoutManager(mLayoutManager);
recipeList.setItemAnimator(new DefaultItemAnimator());
recipeList.setAdapter(adapterRecipe);
submit = (Button) findViewById(R.id.create);
// perform click event on submit button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreatePlan();
}
});
}
public void ListRecipes() {
listRecipe.clear();
SQLiteDatabase db = (new DatabaseManager(this).getWritableDatabase());
String selectQuery = " SELECT recipe_name, image, image2, category" + " FROM " + DatabaseManager.TABLE_RECIPE + " GROUP BY recipe_name";
c = db.rawQuery(selectQuery, null);
Log.d("Query", selectQuery);
if (c.moveToFirst()) {
do {
com.stu54259.plan2cook.Model.Category category = new com.stu54259.plan2cook.Model.Category();
category.setRecipe_name(c.getString(c.getColumnIndex("recipe_name")));
category.setImage(c.getInt(c.getColumnIndex("image")));
category.setImage2(c.getString(c.getColumnIndex("image2")));
category.setCategory_name(c.getString(c.getColumnIndex("category")));
listRecipe.add(category);
} while (c.moveToNext());
c.close();
}
}
public void CreatePlan(){
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
db.createPlanRecipe(d_name, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, id);
}
}

Retrieve data from a List

Sorry if the heading is misleading, i couldn't quite put it in words.
Rotten Tomatoes
The list runs fine and looks fine for what i am doing. What i am planning on doing is have a details page now with the synopsis etc. I thought about passing the ID of the movie that is passed on.
If i click on a movie, how can i, in the next page set the image of that movie, the text etc. Basically get all the data i need from the selected movie?
The source code can be found here - Github
Screenshot (Terrible looking but its just messing around):
Thanks
I was having the same problemm in my project but your seems similar so i will give you my solution in order to help.
In my case i was retrieving stocks from a database and each stock had extra 15 prices which i wanted to show everytime i tapped on a stock so check the below answer.
Code:
I created an OBject with String[] to help me retrieve all those 15 prices for each stock and then pass it through Intent.
public class StockList {
private String stockCurrentName;
private String stockCurrentPrice;
private String stockImage;
private String[] restPrices;
public StockList(String stockCurrentName, String stockCurrentPrice, String stockImage, String[] restPrices) {
this.stockCurrentName = stockCurrentName;
this.stockCurrentPrice = stockCurrentPrice;
this.stockImage = stockImage;
this.restPrices = restPrices;
}
public String getStockCurrentName() {
return stockCurrentName;
}
public void setStockCurrentName(String stockCurrentName) {
this.stockCurrentName = stockCurrentName;
}
public String getStockCurrentPrice() {
return stockCurrentPrice;
}
public void setStockCurrentPrice(String stockCurrentPrice) {
this.stockCurrentPrice = stockCurrentPrice;
}
public String getStockImage() {
return stockImage;
}
public void setStockImage(String stockImage) {
this.stockImage = stockImage;
}
public String[] getRestPrices() {
return restPrices;
}
public void setRestPrices(String[] restPrices) {
this.restPrices = restPrices;
}
}
Then is how i retrieved the data:
public class JsonReadTask extends AsyncTask<String, Void, String> {
public JsonReadTask() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListLoaderActivity.this);
pDialog.setTitle(R.string.waiting);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage(getString(R.string.get_stocks));
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrawer();
pDialog.dismiss();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}
public void ListDrawer() {
customList = new ArrayList<StockList>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
//for each stock i get its prices.
//In your List for each movie you can get its synopsis and anything else you need.
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
price1 = jsonChildNode.optString("price1");
price2 = jsonChildNode.optString("price2");
price3 = jsonChildNode.optString("price3");
price4 = jsonChildNode.optString("price4");
price5 = jsonChildNode.optString("price5");
price6 = jsonChildNode.optString("price6");
price7 = jsonChildNode.optString("price7");
price8 = jsonChildNode.optString("price8");
price9 = jsonChildNode.optString("price9");
price10 = jsonChildNode.optString("price10");
price11 = jsonChildNode.optString("price11");
price12 = jsonChildNode.optString("price12");
price13 = jsonChildNode.optString("price13");
price14 = jsonChildNode.optString("price14");
price15 = jsonChildNode.optString("price15");
image = jsonChildNode.optString("image");
justPrices = new String[]{price1, price2,
price3, price4, price5, price6, price7, price8, price9,
price10, price11, price12, price13, price14, price15};
loipesTimes = new String[]{"1st Day Value " + price1, "2nd Day Value " + price2, "3rd Day Value " + price3, "4th Day Value " + price4, "5th Day Value " + price5,
"6th Day Value " + price6, "7th Day Value " + price7, "8th Day Value " + price8, "9th Day Value " + price9,
"10th Day Value " + price10, "11th Day Value " + price11, "12th Day Value " + price12, "13th Day Value " + price13, "14th Day Value " + price14, "15th Day Value " + price15};
customList.add(new StockList(name, price, image, justPrices));
}
} catch (Exception e) {
Intent intent1 = new Intent(ListLoaderActivity.this,
RefreshActivity.class);
startActivity(intent1);
ListLoaderActivity.this.finish();
}
ArrayAdapter adapter = new MyStocksAdapter(ListLoaderActivity.this, R.layout.list_item, customList);
adapter.notifyDataSetChanged();
startList.setAdapter(adapter);
}
And then pass the through Intent
private void registerCallClickBack() {
startList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
tv1 = (TextView) viewClicked.findViewById(R.id.stock_name);
tv2 = (TextView) viewClicked.findViewById(R.id.stock_price);
Intent intent = new Intent(ListLoaderActivity.this, StockItem.class);
intent.putExtra("name", tv1.getText().toString());
intent.putExtra("price", tv2.getText().toString());
intent.putExtra("stockInfo", customList.get(position).getRestPrices());
intent.putExtra("stockImage", customList.get(position).getStockImage());
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);
}
}
}
I guess you can use it like this and this will help you get it done!!!
Hope i helped you!!!
if you show us what are you doing in your code we could help you more but to pass data from one activity to another you can use intent example :
String value= getIntent().getStringExtra("keyName");
Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);
intent.putExtra("keyName", value);
startActivity(intent);
You should do something like this:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
YourObject item = arraylist.get(arg2);
TextView textView = (TextView) arg1.findViewById(R.id.textView);
Intent intent = new Intent(ThisActivity.this, SecondActivity.class);
intent.putExtra("textview_value", textView.getText().toString());
startActivity(intent);
}
}
});
you can use intent for pass data from one activity to another exactly how Moudiz say and then retrieve received data like this
String value;
Intent intent = getIntent();
value = intent.getStringExtra("keyName");
If you would have pasted your code then it would be easier to understand your actual problem . But with the data and json given :
1.if you having problem in retrieving data from Json then please follow below link :
http://www.androidhive.info/2012/01/android-json-parsing-tutorial
If passing to next Activity then it would be done using Intent:
String value= getIntent().getStringExtra("Key");
Intent intent = new Intent(this, DataClassNameHere.class);
intent.putExtra("key", value);
startActivity(intent);

What does requestCode and resultCode in onActivityResult refer to?

Good day guys. I'm new to android and now using startActivityForResult in my program. In my app, I have two button and two textView. The two button used to open the dialog. How can I check which button was pressed onActivityResult so that the TextView can be setText accordingly to the button?
int a1 = 1;
int a2 = 2;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a1);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialogRadio(a2);
}
});
public void AlertDialogRadio(final int k) { //parameter k is never used
final CharSequence[] ClaimsModel = {"Project", "Petrol", "Car Maintenance"
, "Medical", "Other"};
AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
alt_bld.setTitle("Select a Claims");
alt_bld.setSingleChoiceItems(ClaimsModel, -1, new DialogInterface
.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, 0);
} else if (item == 1) {
Intent intent = new Intent(getActivity().getApplicationContext(), Petrol.class);
startActivityForResult(intent, 1);
} else if (item == 2) {
Intent intent = new Intent(getActivity().getApplicationContext(), CarMainten.class);
startActivityForResult(intent, 2);
} else if (item == 3) {
Intent intent = new Intent(getActivity().getApplicationContext(), Medical.class);
startActivityForResult(intent, 3);
} else if (item == 4) {
Intent intent = new Intent(getActivity().getApplicationContext(), Other.class);
startActivityForResult(intent, 4);
}
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) { // if button1 was clicked
switch (requestCode) {
case 0:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
c.setText(" " + b + "------" + "RM " + result);
Toast.makeText(getActivity(), "Not completed ", Toast.LENGTH_LONG).show();
break;
case 1:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
c.setText(" " + b1 + "------" + "RM " + result1);
break;
case 2:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
c.setText(" " + b2 + "------" + "RM " + result2);
break;
case 3:
String result3 = data.getStringExtra("text");
String b3 = data.getStringExtra("a");
c.setText(" " + b3 + "------" + "RM " + result3);
break;
case 4:
String result4 = data.getStringExtra("text");
String b4 = data.getStringExtra("a");
c.setText(" " + b4 + "------" + "RM " + result4);
break;
}
}
else if (resultCode == 2) { // if button2 was clicked
switch (requestCode) {
case 0:
String result = data.getStringExtra("text");
String b = data.getStringExtra("a");
d.setText(" " + b + "------" + "RM " + result);
break;
case 1:
String result1 = data.getStringExtra("text");
String b1 = data.getStringExtra("a");
d.setText(" " + b1 + "------" + "RM " + result1);
break;
case 2:
String result2 = data.getStringExtra("text");
String b2 = data.getStringExtra("a");
d.setText(" " + b2 + "------" + "RM " + result2);
break;
case 3:
String result3 = data.getStringExtra("text");
String b3 = data.getStringExtra("a");
d.setText(" " + b3 + "------" + "RM " + result3);
break;
case 4:
String result4 = data.getStringExtra("text");
String b4 = data.getStringExtra("a");
d.setText(" " + b4 + "------" + "RM " + result4);
break;
}
}
}
So my program should work like this:
If button1 was clicked....c.setText();
If button2 was clicked....d.setText();
But the program now is nothing display on the TextView. Did the error came from if (resultCode == 1) and else if (resultCode == 2) ?? Thanks a lot
Assume the use select Project1.class
Project1.class
public class Project1 extends AppCompatActivity {
private static String text;
private static String a;
private static EditText txt;
private int g;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
txt= (EditText)findViewById(R.id.editText36);
Button b=(Button)findViewById(R.id.button17);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent returnIntent = new Intent();
a="Project";
text = txt.getText().toString();
returnIntent.putExtra("text", text);
returnIntent.putExtra("a",a);
// returnIntent.putExtra("k",getIntent().getExtras().getString("k"));
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
});
}
}
request_code is the calling function identity, from where it is requested, result_code is the called function identifier, also it specifies status of the called message as Intent.ACTIVITY_OK and so on.
You should avoid using the literal code here.
if (resultCode == 1)
much better to use the named constant --
if (resultCode == RESULT_OK) {
RESULT_OK is -1, so that might be your issue.
Once I set all my request codes the same. Didn't work.
Seems your request codes are different, I'm used to seeing them like this:
private static final int REQUEST_CODE_THIS = 0;
private static final int REQUEST_CODE_THAT = 1;
private static final int REQUEST_CODE_THE_OTHER = 1003;
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
Intent intent = new Intent(getActivity().getApplicationContext(), Project1.class);
startActivityForResult(intent, REQUEST_CODE_THIS);
Check if changing the onActivityResult() like this might help.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE_THIS) { // if button1 was clicked
switch (resultCode == RESULT_OK) {
case 0:
...
}

Android in app Billing to Unlock all Features

I followed a guide to enter the in app purchase and unlock all features. The procedure to purchase works well.
I explain what I do: I added a check in my database, which counts the number of records in a table, if the number is> = 1, I open an activity for purchase in the app. Once purchased, through the method getPurchases, control the purchase, if it was done I open the activity, otherwise I open the activity for purchase. I created this code peril control but I get error:
08-11 18:08:18.120: W/ContextImpl(19293): Implicit intents with startService
are not safe: Intent {
act=com.android.vending.billing.InAppBillingService.BIND }
android.content.ContextWrapper.bindService:529
main.Elenco_F_Fragment.Controlla_record_per_acquisto:243
main.Elenco_F_Fragment.access$9:233
this is the row 243:
final boolean blnBind = getActivity().bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
this is the code for the control
private void Controlla_record_per_acquisto(){
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String controllo = "SELECT COUNT(_id) FROM tbf";
Cursor c = db.rawQuery(controllo, null);
while (c.moveToNext()){
int numero_id = c.getInt(0);
if(numero_id >=1){
// Bind Service
final boolean blnBind = getActivity().bindService(new Intent(
"com.android.vending.billing.InAppBillingService.BIND"),
mServiceConn, Context.BIND_AUTO_CREATE);
if (!blnBind) return;
if (mService == null) return;
Bundle ownedItems;
try {
ownedItems = mService.getPurchases(3, getActivity().getPackageName(), "inapp", null);
Intent intent = null;
intent = new Intent(getActivity(), Crea_e.class);
startActivity(intent);
} catch (RemoteException e) {
e.printStackTrace();
Toast.makeText(context, "getPurchases - fail!", Toast.LENGTH_SHORT).show();
Log.w(tag, "getPurchases() - fail!");
return;
}
int response = ownedItems.getInt("RESPONSE_CODE");
Toast.makeText(context, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response), Toast.LENGTH_SHORT).show();
Log.i(tag, "getPurchases() - \"RESPONSE_CODE\" return " + String.valueOf(response));
if (response != 0) return;
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_ITEM_LIST\" return " + ownedSkus.toString());
Log.i(tag, "getPurchases() - \"INAPP_PURCHASE_DATA_LIST\" return " + purchaseDataList.toString());
Log.i(tag, "getPurchases() - \"INAPP_DATA_SIGNATURE\" return " + (signatureList != null ? signatureList.toString() : "null"));
Log.i(tag, "getPurchases() - \"INAPP_CONTINUATION_TOKEN\" return " + (continuationToken != null ? continuationToken : "null"));
}else {
Intent intent = null;
intent = new Intent(getActivity(), InAppBillingActivity.class);
startActivity(intent);
}
c.close();
db.close();
}
}
EDIT--------------------------------------------
private void Controlla_record_per_acquisto(){
SQLiteDatabase db = new DatabaseHelper(getActivity()).getReadableDatabase();
String controllo = "SELECT COUNT(_id) FROM FTB";
Cursor c = db.rawQuery(controllo, null);
while (c.moveToNext()){
int numero_id = c.getInt(0);
if(numero_id >=1){
Intent intent = null;
intent = new Intent(getActivity(), InAppBillingActivity.class);
startActivity(intent);
}else {
Intent intent = null;
intent = new Intent(getActivity(), Cure.class);
startActivity(intent);
}
c.close();
db.close();
}
}
I would suggest you to use the new Billing system, with the IabHelper class there you can do what you have described above both async/sync without the needs for "extra" code really.
http://developer.android.com/training/in-app-billing/preparing-iab-app.html

Categories