I'm using this code to show images from url in list view so im using this class that extended from simpleAdapter
package com.mypackage.lebadagency;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
public class MyAdapter extends SimpleAdapter {
public MyAdapter(Context context, List<? extends Map<String, ?>> data,
int resource, String[] from, int[] to) {
super(context, data, resource, from, to);
// TODO Auto-generated constructor stub
}
#Override
public void setViewImage(ImageView v, String value) {
UrlImageViewHelper.setUrlDrawable(v, value);
}
}
and using it is like :
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new MyAdapter(
EconomyPanel.this, contactList,
R.layout.economy_list_item, new String[] {TAG_ID, TAG_IMAGE_URL,TAG_NAME
}, new int[] {R.id.idTV, R.id.image1,
R.id.name });
setListAdapter(adapter);
}
my list load 10 items, my problem is that it does not load all the 10 images , sometimes it only loads one of them , what is the problem and how to fix it ??
The problem is not with this code , this code is working no need to change the method of viewing the image or anything the problem is simpler than that , any image that contain space gab in its file name , the browsers can handle it by replacing the space with %20 , and when android retrieve the image url it retrieve it without the 20% symbol , so i need to add this command to the url :
value=value.replaceAll(" ", "%20");
and then
UrlImageViewHelper.setUrlDrawable(v, value);
Related
Getting error at NewActivity, as getting error while adding the data in array list and loading it to recycler view. Iam working on a project where I have to load Room data in recycler view. I am getting an error in for loop .. tried using foreach still getting tge same error. Error is showing while using add method to load a data from list to arraylist
package com.app.mycontacts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Adapter;
import com.app.mycontacts.AddContactActivity.AddContactActivity;
import com.app.mycontacts.Data.ContactDetails;
import com.app.mycontacts.Data.ContactRepository;
import com.app.mycontacts.Data.MyAdapterClass;
import com.app.mycontacts.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
public class NewActivity extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
ArrayList<ContactDetails> contactarrayList;
RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView= findViewById(R.id.reyclerview);
new LoadDataTask().execute();
}
class LoadDataTask extends AsyncTask<Void,Void,Void> {
ContactRepository contactRepository;
List<ContactDetails> contactList1;
#Override
protected void onPreExecute() {
super.onPreExecute();
contactRepository = new ContactRepository(getApplicationContext());
}
#Override
protected Void doInBackground(Void... voids) {
contactList1=contactRepository.getContactsDetails();
contactarrayList= new ArrayList<ContactDetails>();
for(int i=0; i<=contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
super.onPostExecute(unused);
recyclerView.setLayoutManager(new LinearLayoutManager(NewActivity.this));
MyAdapterClass myAdapterClass= new MyAdapterClass(NewActivity.this,contactarrayList);
recyclerView.setAdapter(myAdapterClass);
}
}
}
Tried debugging the code, app is getting crash at the above stage.. Expecting to display the data inserted at room db.
You are indexing wrong in the loop.
The size of the list is 4 but Java indexes from 0. So if you have 4 elements it goes [0], [1], [2], [3]
for(int i=0; i<=contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
What you are doing is reaching for the fifth element - [0], [1], [2], [3], [4].
This will work:
for(int i=0; i < contactList1.size();i++){
contactarrayList.add(contactList1.get(i));
}
But you don't need to iterate it, you should be able to just call .addAll.
contactarrayList.addAll(contactList1);
I am a beginner, building a goofy app that uses an online API. I uploaded the .json file to GitHub, from where my app accesses it and gives the output. However, it always runs the statements for onErrorResponse. Am I doing something wrong?
Here's the code for MainActivity:
package com.example.jsonparsing;
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
RequestQueue requestQueue;
Button search;
EditText input;
TextView word;
TextView meaning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = findViewById(R.id.button_getMeaning);
input = findViewById(R.id.editText_input);
word = findViewById(R.id.textView_word);
meaning = findViewById(R.id.textView_meaning);
requestQueue = Volley.newRequestQueue(this);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String term = input.getText().toString().toLowerCase();
String displayInput = term.toUpperCase() + ":";
word.setText(displayInput);
JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, "https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String definition = response.getString(term);
meaning.setText(definition);
} catch (JSONException e) {
e.printStackTrace();
meaning.setText("Sorry, this word doesn't exist in the boner database.");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Connection error, please check internet connection.", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonObjectRequest1);
}
});
}
}
The project uses Volley and I have added Internet permission in the manifest.
Edit: here's the .json :
https://github.com/DeathVenom54/bonerDictionaryDatabase/blob/master/definitions.json
The json url you have posted is a link to someone's github page with the json, but not the json itself. Whats most likely happening is volley is downloading the HTML page in its entirety which contains the json. Its then complaining that its not correctly formatted json.
If you want that json directly you need to find a way to host it somewhere. For example github has an api that you can access json files like this https://api.github.com/users/mralexgray/repos
For local testing you could always copy it into a local json file and import into the res/raw of your app and reference it from there.
I am wondering how to when the user closes the app, save the markers to a file then load them back in when the app is opened again
Here is my code:
package com.example.mapapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.OverlayItem;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends Activity
{
MapView mv;
StringBuffer filePath;
File file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// This line sets the user agent, a requirement to download OSM maps
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
setContentView(R.layout.activity_main);
mv = (MapView)findViewById(R.id.map1);
ItemizedIconOverlay<OverlayItem> items;
mv.setBuiltInZoomControls(true);
mv.getController().setZoom(11);
mv.getController().setCenter(new GeoPoint(53.3710,-1.4502));
}
public boolean onOptionsItemSelected(MenuItem item)
{
if(item.getItemId() == R.id.addpoi)
{
// react to the menu item being selected...
Intent intent = new Intent(this,AddPoi.class);
startActivityForResult(intent,0);
return true;
}
Intent intent = new Intent(this,AddPoi.class);
startActivityForResult(intent,0);
return false;
}
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_mad_assignment, menu);
return true;
}
protected void onActivityResult(int requestCode,int resultCode,Intent intent)
{
if(requestCode==0)
{
if (resultCode==RESULT_OK)
{
Bundle extras=intent.getExtras();
String poiName= extras.getString("poiName");
String poiType= extras.getString("poiType");
String poiDesc= extras.getString("poiDesc");
ItemizedIconOverlay<OverlayItem> items = new ItemizedIconOverlay<>(this, new ArrayList<OverlayItem>(), null);
OverlayItem marker = new OverlayItem(poiName, poiType,poiDesc, new GeoPoint(53.3710,-1.4502));
items.addItem(marker);
mv.getOverlays().add(items);
Log.d("NAME",poiName);
Log.d("NAME",poiType);
Log.d("NAME",poiDesc);
}
}
}
}
Add marker code:
package com.example.mapapp;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import com.example.luke.madassignment.R;
public class AddPoi extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_poi);
Button addPoiButton = (Button)findViewById(R.id.addPoi);
Button cancelButton = (Button)findViewById(R.id.cancel);
addPoiButton.setOnClickListener(this);
cancelButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent();
Bundle bundle=new Bundle();
EditText poiName = (EditText)findViewById(R.id.editTextPoiName);
EditText poiType = (EditText)findViewById(R.id.editTextPoiType);
EditText poiDesc = (EditText)findViewById(R.id.editTextPoiDesc);
String poiNameString = poiName.toString();
String poiTypeString = poiName.toString();
String poiDescString = poiName.toString();
bundle.putString("poiName",poiNameString);
bundle.putString("poiType",poiTypeString);
bundle.putString("poiDesc",poiDescString);
intent.putExtras(bundle);
setResult(RESULT_OK,intent);
finish();
}
}
The problem is i cant figure out a way to save the users marker to a file if the app is closed and then load back in the markers when the app is opened again
Use built in sharedPref, simple key value storage, to save data in persistence mode. Check doc here
The SharedPreferences class provides a general framework that allows
you to save and retrieve persistent key-value pairs of primitive data
types. You can use SharedPreferences to save any primitive data:
booleans, floats, ints, longs, and strings. This data will persist
across user sessions (even if your application is killed).
https://developer.android.com/guide/topics/data/data-storage.html#pref
Using OSMBonusPack, you can grab your markers in a KML structure, then save the KML file locally (in onStop).
And load back this KML file when the app is opened (in onCreate).
My android application is kind of a text editor. I want to display the list of saved files. But whenever the activity listing the files is called, the activity stops. This code works completely fine when run in emulator but not on the actual device. Debugging the application on phone shows that the app stops when it tries to access the path although no error is displayed in logcat.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class File_List extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
Drawable background=getResources().getDrawable(R.drawable.background);
background.setAlpha(100);
final ListView list=(ListView)findViewById(R.id.listView1);
File folder = new File("/data/data/com.example.demo/files"); //for accessing the folder conatining the files
File[] listOfFiles = folder.listFiles(); //for listing the files within the folder
ArrayList<String> liste = new ArrayList<String>();
for(int i=0;i<listOfFiles.length;i++)
{
if(listOfFiles[i].isDirectory()==false)
liste.add(listOfFiles[i].getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, liste);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
// TODO Auto-generated method stub
//Log.e("selected",list.getAdapter().getItem(position).toString());
Common.CommonVar=2;
File file=new File("/data/data/com.example.demo/files/"+list.getAdapter().getItem(position).toString());
String content;
Log.e("file access", file.getName());
try
{
content = new Scanner(file).useDelimiter("\\A").nextLine();
Intent intent=new Intent(File_List.this,MainActivity.class);
intent.putExtra("File_data",content);
startActivity(intent);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Change the line as follows
File folder = new File("/data/data/com.example.demo/files");
if(!folder.exists()){
folder.mkdir();
}
I have two String[], one with names and the other one with phone number. If I select one name from list, how can I call phone number of that person from Dialog box. For example, first person in first string[] has a phone number of second[]. How to get that number?
package com.mkyong.android;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ListFruitActivity extends ListActivity {
static final String[] Imena = new String[] { "Aleksandar Panic", "Dubravka Protic", "Milutin Panic",
"Jelica Panic", "Nemanja Gagic", "Doris Dragojevic", "Milica Protic", "Kiki Beba",
"Dule Savic", "Miroslav Miskovic", "Petar Djuric", "Dragoslav Joksimovic", "Petar Petrovic" };
static final String[] Brojevi=new String[] { "0638638045", "062450050", "065045324", "05443",
"06535475", "564218", "546567", "514574","5454333","444787","413133","354867","24879"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_fruit,
Imena));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(ListFruitActivity.this);
adb.setTitle("Odabir");
adb.setMessage("Izabrali ste profesora "+parent.getItemAtPosition(position));
adb.setPositiveButton("Call",new DialogInterface.OnClickListener() {
public void onClick (DialogInterface dialog, int which) {
Intent i=new Intent(android.content.Intent.ACTION_DIAL,
Uri.parse("tel:+651234567")); //here is the problem, how to get the right number
startActivity(i);
}
});
adb.show();
}
});
}
}
Why do you need two String[] arrays?
You have two options to implement it in a better way:
Use a Map<String, String> to store name as key and phone number as value.
Create a class Contact to store all your contact details like name, address, phone number, email etc and then use a List<Contact> or an array (recommended way of doing this).