I'm creating an android chat app.. The main screen will be a list of messages.. I get the messages and the friends from the database then show it in my list which contains two textviews and 1 imageview.. every thing works fine, but when i get my friends from database(not the same size of messages) and I need to get Imagepath of each friend.. that works fine also when i log it.. but when I try to get it in the adapter i get my list with only one unit..
messages_iv = (ImageView) row.findViewById(R.id.imageView1);
final String name = items.get(position).getTitle();
final String photoUrl = friends.get(1).getPhotoUrl();
new Thread(new Runnable() {
public void run() {
Log.d("Button Clicked", "Name: " + name);
Log.d("Button Clicked", "URL: " + photoUrl);
getPhoto(messages_iv, photoUrl);
}
}).start();
when I try friends.get(0) it works fine.. but when I try friends.get(1) I get :
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
Any Idea ??
Thanks.
Related
I have problem about getting data from multiple activities.
Here's my problem.
I made 3 Activities to get data from each other.(Let me say 3 Activities A,B,C)
A, B execute different method but their results are same type, the ArrayList.
I have a purpose to get both results in C from A,B.
Activity-A
Intent intent = new Intent(RouteInfoDebug1.this, LiveLocationInfo.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("stdid", (ArrayList<String>) list);
intent.putExtras(bundle);
Log.d("LLNC", "Passed Value:" + (ArrayList<String>) list +"\n");
startActivity(intent);
Activity-B
Intent intent = new Intent(LowBusInfo.this, LiveLocationInfo.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("lowStdid", (ArrayList<String>) list);
intent.putExtras(bundle);
Log.d("LLLC", "Passed Value:" + (ArrayList<String>) list +"\n");
startActivity(intent);
Activity-C
Bundle bundle = getIntent().getExtras();
ArrayList<String> list = bundle.getStringArrayList("stdid");
Log.d("LLNC", "Received Value: " + bundle.getStringArrayList("stdid")+"\n");
ArrayList<String> lowList = bundle.getStringArrayList("lowStdid");
Log.d("LLLC", "Received Value: " + bundle.getStringArrayList("lowStdid")+"\n");
I coded like this.
When I checked each values(Passed Value from Log.d) from different Activities A,B, it was perfect.
From A list: [null, 305001086, 305001087]
From B list: [null, 305001233, 305001241, 305001010, 305001123, 305001239, 305001273, 305001340, 305001143, 305001352, 305200048, 305001269, 305001275, 305001345, 305001167, 305001237, 305001434, 305001235, 305001354, 305001136, 305001227, 305001094, 305001243, 305001380, 305000887, 305001159, 305001347, 305001247, 305001353, 305001346, 305001171, 305001231, 305001169, 305001086, 305001127, 305200003, 305001341, 305001274, 305001245, 305001155, 305001088, 305001342, 305001271, 305200054, 305001229, 305300257, 305001137, 305001165, 305001153, 305001163]
But the problem is in Activity-C.
I keep getting null from one activity. For example, I get null from B list when I get full A list Value or the opposite situation happens.
I googled whole day finally I found someone says two activities can't be started at once so I matched key the same. But the result was miserably same thing.
Here's the detail purpose:
I wanted to get each data from A,B in C after that I wanted to make condition between A List and B List, refine it and use the code to get other data.
Actually I divided activities because of my convenience. If I combine two activities(A,B) into one(but different classes), could be the solution? This is my first question sorry for too long. Thanks in advance.
This runs Activity A then play Activity B.
public void mOnClick(View view){
switch(view.getId()){
case R.id.btnSearch:
new Thread(new Runnable(){
#Override
public void run(){
data = getRouteInfo();
/*Activity B's Method will be executed here*/
LowBusInfo lowBusInfo = (LowBusInfo)getApplication();
lowBusInfo.getLowBusInfo();
lowBusInfo.thread.start();
thread.start();
runOnUiThread(new Runnable(){
#Override
public void run(){
textView.setText(data);
}
});
}
}).start();
break;
}
}
Some background:
I have a map where I allow the user to click and select a place. Then I am getting the address from the place where they clicked.
What I want to do: Using that address, which is a String, I want to get details about that place by using the new Google Map Places API.
I'm attempting to do this with the code below
//Make the Autocomplete request builder with the String address
FindAutocompletePredictionsRequest.Builder requestBuilder =
FindAutocompletePredictionsRequest.builder()
.setQuery(address)
.setTypeFilter(TypeFilter.ADDRESS);
placesClient = Places.createClient(getApplicationContext());
//Create the Autocomplete Task
Task<FindAutocompletePredictionsResponse> task =
placesClient.findAutocompletePredictions(requestBuilder.build());
task.addOnSuccessListener(new OnSuccessListener<FindAutocompletePredictionsResponse>() {
#Override
public void onSuccess(final FindAutocompletePredictionsResponse findAutocompletePredictionsResponse) {
//Use the response to get a list of Predictions
List<AutocompletePrediction> list = findAutocompletePredictionsResponse.getAutocompletePredictions();
if (list.isEmpty() || list == null) {
} else {
//Get the first Autocomplete prediction and later, it's ID.
AutocompletePrediction ap = list.get(0);
//Provide a list of Place Fields that I want to retrieve.
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS);
//Make the request to fetch the place using the Place ID obtained from the Autocomplete prediction.
FetchPlaceRequest request = FetchPlaceRequest.builder(ap.getPlaceId(), placeFields).build();
placesClient = Places.createClient(getApplicationContext());
//Using the Place ID from the Autocomplete prediction, make a request to fetch places.
placesClient.fetchPlace(request).addOnSuccessListener(new OnSuccessListener<FetchPlaceResponse>() {
#Override
public void onSuccess(FetchPlaceResponse fetchPlaceResponse) {
//Use the response to get the Place Object
Place place = fetchPlaceResponse.getPlace();
//Display the results from the Place Object
displayResults("\n-----------------\nName: " + place.getName() + "\nAddress: " + place.getAddress());
}
}).addOnFailureListener(new OnFailureListener() {
//......
});
}
}
});
task.addOnFailureListener(new OnFailureListener() {
//......
});
Problem: The problem is that when I do this and use place.getName(), instead of displaying the location's name, as it should, it displays the first part of the address like the street number and name. Additionally, other Fields like the phone number and opening hours are null.
Does anybody know how I can get the Place Object from the String address?
Getting details about the place where the user clicks is the most important feature of my Android app.
I am using the new Places API since the Place Details and Place Picker are now deprecated.
In my program i am using ListView and in each and every row i am showing one of the image icon (Yes/No) based on condition i am playing with, and using below code to get total number of item(s) in a list (includes both :- Yes & No) Icons.
String totalNumberOfItemsInAList = ""+ lstView.getAdapter().getCount();
Toast.makeText(getApplicationContext(), "Total number of Items are:" + totalNumberOfItemsInAList, Toast.LENGTH_LONG).show();
But what if i only want to know total number of items in a list which contains Yes Icon, my code looks like this:
private SparseBooleanArray flags = new SparseBooleanArray();
// to upload whole list
for(int position = 0; position < lstView.getAdapter().getCount(); position++)
{
flags.put(position, true);
}
((BaseAdapter) lstView.getAdapter()).notifyDataSetChanged();
}
});
/*** Get Images from SDCard ***/
listSDCardImages = fetchSDCardImages();
// ListView and imageAdapter
lstView = (ListView) findViewById(R.id.listSDCardImages);
lstView.setAdapter(new ListSDCardImagesAdapter(this));
Toast.makeText(getApplicationContext(), "Total number of Items are:" + String.valueOf(position), Toast.LENGTH_LONG).show();
}
Condition, i am using to show Yes/No icons is something like this:
if(resultAvailable)
{
holder.colView.setImageResource(R.drawable.icon_yes);
}
else
{
holder.colView.setImageResource(R.drawable.icon_no);
}
Use
yesImagesCount=0;
variable in your activity and increment this count in this code as
if(resultAvailable)
{
holder.colView.setImageResource(R.drawable.icon_yes);
yesImagesCount++;
}
else
{
holder.colView.setImageResource(R.drawable.icon_no);
}
And Finally display toast as
Toast.makeText(getApplicationContext(), "Total number of Yes Icons are:" + String.valueOf(yesImagesCount), Toast.LENGTH_LONG).show();
I'm new to Parse and was wondering if there is any way to store all the ParseFiles (in this case images) for a given ParseUser into something like an ArrayList?
Here's my code:
public ArrayList<ParseFile> getFiles() {
ArrayList<ParseFile> files = new ArrayList<ParseFile>();
//mUser is the current ParseUser
ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername());
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> fileList, ParseException e) {
if (e == null) {
Log.d("FILES", "Retrieved " + fileList.size() + " files");
for(ParseObject ch:fileList) {
image = ch.getParseFile("image");
files.add(image);
#Override
public void done(byte[] arg0, ParseException arg1) {
//nothing to do here
}
});
}
Log.i("TAG", ": " + files.size());
} else {
Log.d("FILES", "Error: " + e.getMessage());
}
}
});
Log.i("DONE", ": " + files.size());
return files;
}
When I'm inside done(), the 3 images I have for this particular user are added and I get an ArrayList of size 3 which is to be expected. When I'm outside of done(), the size of the ArrayList goes back to 0, which I'm assuming is because it's being referenced outside of the query. And sure enough it returns an empty ArrayList (not too shocking).
I feel like this should be an easy solution but I can't seem to figure it out. I've tried to make a static ArrayList variable but that doesn't seem to work either. Any idea on how to return the desired ArrayList?
I believe the problem is that the outside thread still continues before your background process is completed. In other words..
1. query.findInBackground(....);
2. Log.i("DONE" ....);
.. 2. is executed before 1. completes. The whole point of Parse "inBackground" is that it completes actions that your thread is not dependent on. If you need to do something with the List, you should do it in the same thread as the background thread or not do it "inBackground".
Try like this
ParseQuery<ParseObject> query = ParseQuery.getQuery(mUser.getUsername());
List<ParseObject>imageList=query.find();
try {
Arraylist<ParseFile> files = new Arraylist<ParseFile>files();
ParseFile image;
for(int i =0;i<imageList.size();i++)
{
image = imageList.get(i).getParseFile("image");
files.add(image);
}
}
catch()
{
}
I have an odd problem, (see shorter version at the bottom first please)
When my activity starts for the first time, the listview shows the dataset fine. The adapter is a custom adapter which shows 2 rows of text and an image. I call an asynctask upon a click event to the listview, the dataset updates in accordance with whatever was clicked on in the listview - more specifically the arrays which are associated with the adapter become rewritten with the parsings of some xml, and then notifyachapterdatasetchanged method is called to update the listview in the onPostExecute function. However I always get NullPointerException when I am iterating through some xml (which is very well formed and validates). ALso its worth mentioing that the algorithm that parses the desired values is good, because as mentioned above, if i write to just 1 element of the array then I dont get the error I just get the last node value so its looping in the correct places. i.e If I simple try to copy the current node value I am parsing during the loop into, say, producyTypes[0] then the last value from within the loop actually makes it to the listview as it constantly overwrites this elemet of the array
Here is my code.`
public class main extends Activity implements OnItemClickListener
{
String selectedType="";
ListView lview3;
ImageView iv;
ListViewCustomAdapter adapter;
String test = "";
List<String> ls;
String productTypes[] = {"Monitor","Components","Systems","Laptops","Flash / Usb Memory",
"Networking","Cables","Peripherals","Sound and Vision", "Software"};
String productsIncluded[] = {"Sizes (inches) 17, 19, 20",
"Motherboards, PSU, Cases, Fans/Heatsinks/Coolers, Barebones Systems, Blue-Ray/DVD. Card Readers, Controller Cards, Drive Enclosures, Sound Cards",
"Bundles, Switches and Hubs, Print Servers, Accessories/Modules",
"Cables for: Drives, Networking, HDMI/Monitor, Audio/Video, USB/Firewire, Power, Miscellaneous",
"Mice, Connectors, Bluetooth Devices",
"Mp3/Mp4 Solar Panel",
"Anti-Virus, Internet Security, Operating Systems, Office,,
"",
""};
private static int images[] = {R.drawable.monitor, R.drawable.components, R.drawable.systems,
R.drawable.laptops, R.drawable.flashusb, R.drawable.networking, R.drawable.cables, R.drawable.
peripherals, R.drawable.soundandvision, R.drawable.software};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView)findViewById(R.id.ImageView01);
iv.setImageResource(R.drawable.logo);
iv.setVisibility(View.VISIBLE);
lview3 = (ListView) findViewById(R.id.listView3);
adapter = new ListViewCustomAdapter(main.this, productTypes, productsIncluded, images);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(main.this);
}
#Override
public void onItemClick(AdapterView arg0, View arg1, int position, long id) {
selectedType = "";
if(position == 0)
{
selectedType= "Monitors";
}
if(position == 1)
{
selectedType= "Hard Drives";
}
Toast.makeText(this, Integer.toString(position), Toast.LENGTH_SHORT).show();
new async().execute();
/*
Intent intent = new Intent(getApplicationContext(),activitywo.class);
Bundle bundle =new Bundle();
bundle.putString("selectedType",selectedType);
intent.putExtras(bundle);
startActivity(intent);
//Toast.makeText(this, "Title => "+productTypes[position]+" \n Description => "+productsIncluded[position], Toast.LENGTH_SHORT).show();
*/
}
private class async extends AsyncTask<String, Void, Void> {
// UI Thread
protected void onPreExecute() {
}
// automatically done on worker thread (separate from UI thread)
protected Void doInBackground(final String... args) {
try{
Resources res = getResources();
InputStream in;
in = res.openRawResource(R.raw.core);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document dom = builder.parse(in);
Element root = dom.getDocumentElement();
NodeList items = root.getElementsByTagName("entry");
count=0;
for(int i =0;i<items.getLength();i++){
Node item = items.item(i);
NodeList properties = item.getChildNodes();
//productsDefinedByTypeArray = new String[properties.getLength()];
for(int j = 0;j<properties.getLength();j++){
Node property = properties.item(j);
String name = property.getNodeName();
if(name.equalsIgnoreCase("g:product_type")){//everytime we hit g:product_type grab the value
String strText = property.getFirstChild().getNodeValue();
if(strText.contains(selectedType)){
//
for(int k = 0;k<properties.getLength();k++){
Node propertysecond = properties.item(k);
String namesecond = propertysecond.getNodeName();
if(namesecond.equalsIgnoreCase("title")){//everytime we hit title grab the value
String strTextsecond = propertysecond.getFirstChild().getNodeValue();
productTypes[0] = strTextsecond;
yo = strTextsecond;
count++;
}
}
}
}
}
}
The code crashes at the point where I am trying to copy the value of a "title" node that I parse out of my xml file into the list-String-. I am using a list-string- to show that even if you try and copy the value into the array itself (the array that is associated with the adapter), even if you comment out the notifydatasetchanged () line the program still crashes. The xml is well formed and very consistent. I know this because (aecept the fact its really small and I have read it all) ! Why can I not copy every node value into my array/list whilst the loop is in progress?
Any help is massively appreciated. Thank you.
Shorter version:
I cannot write to the List
if(strText.contains(selectedType)){
//
for(int k = 0;k<properties.getLength();k++){
property = properties.item(k);
name = property.getNodeName();
if(name.equalsIgnoreCase("title")){//everytime we hit title grab the value
String strTextsecond = property.getFirstChild().getNodeValue().toString();
ls.add(strTextsecond.toString());
//test = strTextsecond;
}
}
}
Maybe you forget initialize ls? I don't find in your code something like:
ls = new List<String>();