load Image from URL issue - java

I have an onClickListener that should call a class that shows and image from a static url. I put a toast in the called class and that shows but no image. The list.onClickListener should call the class ShowImage which should post an image. Please help I am not sure what I am doing incorrect.
Note* in my main_layout.xml I have an imageview.
package com.flash_tattoo;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity {
ListView list;
LazyAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
JSONArray jsonArray;
try {
jsonArray = new JSONArray(jsonData);
String[] mStrings = new String[jsonArray.length()];
String[] mImages = new String[jsonArray.length()];
String[] mPath = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++)
{
String url = jsonArray.getJSONArray(i).getString(2);
mStrings[i] = "http://www.2020mediaonline.com/tattoo/thumbnail_image/" + url;
String image_name = jsonArray.getJSONArray(i).getString(1);
mImages[i] = image_name;
String path_name = jsonArray.getJSONArray(i).getString(1);
mPath[i] = path_name;
}
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings, mImages);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){
ShowImage go = new ShowImage();
Toast.makeText(MainActivity.this, "In onClick", Toast.LENGTH_LONG).show();
}
});
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
class ShowImage extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
ImageView imgView =(ImageView)findViewById(R.id.ImageView01);
Drawable drawable = LoadImageFromWebOperations("http://www.ansi.okstate.edu/breeds/other/llama/llama1.jpg");
imgView.setImageDrawable(drawable);
Toast.makeText(MainActivity.this, "show big image", Toast.LENGTH_LONG).show();
}
private Drawable LoadImageFromWebOperations(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
#Override
public void onDestroy()
{
adapter.imageLoader.stopThread();
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this,flash_tattoo.class);
startActivityForResult(myIntent, 0);
}
};
}

I suggest you to use AsyncTask to load your bitmap and populate it to your imageView, you can find more details via the following link:
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
Hope this can help you.

You can't use constructor to start new activity. You must use startActivity() for that. So I don't see why you expect ShowImage go = new ShowImage() to do anything. It's just an empty default constructor.

This is what you are looking for. Thanks.

Related

IndexOutOfBoundsException when making one Arraylist equal to another

I am trying to filter my RecyclerView using SearchView by following this guide: https://www.geeksforgeeks.org/searchview-in-android-with-recyclerview/
However, I am getting an IndexOutOfBoundsException when making one Arraylist equal to another, which I believe is happening at this portion of the code here:
public void filterList(ArrayList filteredlist) {
// below line is to add our filtered
// list in our course array list.
book_title = filteredlist;
// below line is to notify our adapter
// as change in recycler view data.
notifyDataSetChanged();
}
Here is the full code for my adapter class:
package com.benjamin.kwok.recipertracker;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
private Context context;
private Activity activity;
private ArrayList book_id, book_title, book_author, book_pages;
CustomAdapter(Activity activity, Context context, ArrayList book_id, ArrayList book_title, ArrayList book_author,
ArrayList book_pages){
this.activity = activity;
this.context = context;
this.book_id = book_id;
this.book_title = book_title;
this.book_author = book_author;
this.book_pages = book_pages;
}
public void filterList(ArrayList filteredlist) {
// below line is to add our filtered
// list in our course array list.
book_title = filteredlist;
// below line is to notify our adapter
// as change in recycler view data.
notifyDataSetChanged();
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.book_title_txt.setText(String.valueOf(book_title.get(position)));
holder.book_author_txt.setText(String.valueOf(book_author.get(position)));
holder.book_pages_txt.setText(String.valueOf(book_pages.get(position)));
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(book_id.get(position)));
intent.putExtra("title", String.valueOf(book_title.get(position)));
intent.putExtra("author", String.valueOf(book_author.get(position)));
intent.putExtra("pages", String.valueOf(book_pages.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return book_id.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView book_id_txt, book_title_txt, book_author_txt, book_pages_txt;
LinearLayout mainLayout;
MyViewHolder(#NonNull View itemView) {
super(itemView);
book_title_txt = itemView.findViewById(R.id.recipe_title_txt);
book_author_txt = itemView.findViewById(R.id.book_description_txt);
book_pages_txt = itemView.findViewById(R.id.recipe_pages_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
}
And the full code for my MainActivity:
package com.benjamin.kwok.recipertracker;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
FloatingActionButton add_button;
FloatingActionButton camera_button;
ImageView empty_imageview;
ImageView imageView;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> recipe_id, recipe_title, recipe_description, recipe_minutes;
CustomAdapter customAdapter;
final static private int NEW_PICTURE = 1;
private String mCameraFileName;
private static final String TAG = "CapturePicture";
static final int REQUEST_PICTURE_CAPTURE = 1;
private String pictureFilePath;
private String deviceIdentifier;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
// SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(this);
// SharedPreferences.Editor editor = mSharedPreference.edit();
// String text= mSharedPreference.getString(getString(R.string.name), "");
//// name_output.setText(text);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
camera_button = findViewById(R.id.camera_button);
empty_imageview = findViewById(R.id.empty_imageview);
imageView = findViewById(R.id.imageView);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddActivity.class);
startActivity(intent);
}
});
camera_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 100);
}
});
myDB = new MyDatabaseHelper(MainActivity.this);
recipe_id = new ArrayList<>();
recipe_title = new ArrayList<>(10);
recipe_description = new ArrayList<>();
recipe_minutes = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(MainActivity.this,this, recipe_id, recipe_title, recipe_description,
recipe_minutes);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
loadData();
}
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
Bundle bundle = data.getExtras();
Bitmap captureImage = (Bitmap) bundle.get("data");
imageView.setImageBitmap(captureImage);
saveToGallery();
}
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image added to Gallery", Toast.LENGTH_LONG);
}
}
private void saveToGallery(){
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
FileOutputStream outStream = null;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath() + "/RecipeImages");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
MediaScannerConnection.scanFile(this, new String[] { outFile.getPath() }, new String[] { "image/jpeg" }, null);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
recipe_id.add(cursor.getString(0));
recipe_title.add(cursor.getString(1));
recipe_description.add(cursor.getString(2));
recipe_minutes.add(cursor.getString(3));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
public void loadData() {
SharedPreferences mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = mPreferences.getString("name","");
setTitle(name+"'s" + " Recipe Tracker");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
// return super.onCreateOptionsMenu(menu);
MenuItem searchItem = menu.findItem(R.id.actionSearch);
// getting search view of our item.
SearchView searchView = (SearchView) searchItem.getActionView();
// below line is to call set on query text listener method.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// inside on query text change method we are
// calling a method to filter our recycler view.
filter(newText);
return false;
}
});
return true;
}
private void filter(String text) {
// creating a new array list to filter our data.
ArrayList filteredlist = new ArrayList<>();
// running a for loop to compare elements.
for (String item : recipe_title) {
// checking if the entered string matched with any item of our recycler view.
if (item.toLowerCase().contains(text.toLowerCase())) {
// if the item is matched we are
// adding it to our filtered list.
filteredlist.add(item);
}
}
if (filteredlist.isEmpty()) {
// if no item is added in filtered list we are
// displaying a toast message as no data found.
Toast.makeText(this, "No Data Found..", Toast.LENGTH_SHORT).show();
} else {
// at last we are passing that filtered
// list to our adapter class.
customAdapter.filterList(filteredlist);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(MainActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
As soon as I start typing in a new search query, this error seems to get thrown.

Get image into ImageView dynamically

What my program is currently doing , it searches in a database for
an ID(inputed by the user), and based on that it displays the title,
and the respective "picture.jpg"(which is just a string).
What I want to do, is I want to take the string(picture.jpg), and use
that to search on the server. So in the end it should be something
like:
http://192.168.1.254/images/picture.jpg. And it should also display the picture.
SecondActivity.java
This is how my whole code looks like:
package br.exemplozxingintegration;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SecondActivity extends AppCompatActivity implements View.OnClickListener {
private EditText pastetext;
private ClipboardManager myClipboard;
private ClipData myClip;
private Button btn;
private EditText textView1;
private Button buttonGet;
private TextView textViewResult;
private ImageView ImageView1;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
pastetext = (EditText) findViewById(R.id.textView1);
btn = (Button)findViewById(R.id.buttonPaste);
btn.performClick();
textView1 = (EditText) findViewById(R.id.textView1);
buttonGet = (Button) findViewById(R.id.buttonGet);
textViewResult = (TextView) findViewById(R.id.textViewResult);
Image = (ImageView) findViewById(R.id.imageView1);
buttonGet.setOnClickListener(this);
}
#SuppressLint("NewApi")
public void paste(View view) {
ClipData cp = myClipboard.getPrimaryClip();
ClipData.Item item = cp.getItemAt(0);
String text = item.getText().toString();
pastetext.setText(text);
Toast.makeText(getApplicationContext(), "Text Pasted",
Toast.LENGTH_SHORT).show();
}
private void getData() {
String qrcode = textView1.getText().toString().trim();
if (qrcode.equals("")) {
Toast.makeText(this, "", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+textView1.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(SecondActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String title="";
String image = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject androidData = result.getJSONObject(0);
title = androidData.getString(Config.KEY_TITLE);
image = androidData.getString(Config.KEY_IMAGE);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Title:\t" + title);//+"\nImagine :\t"+ image);
//int id = getResources().getIdentifier("http://192.168.1.254/2015/380panel/uploads/images/sm/"
+ image, null, null);
//ImageView1.setImageURI(id);
Picasso.with(this).load("http://192.168.1.254/2015/380panel/uploads/images/sm/"
+ image).into(ImageView1);
}
#Override
public void onClick(View v) {
getData();
} }
// }
Easy with Picasso Library:
http://square.github.io/picasso/
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Picasso Library: http://square.github.io/picasso/
Add this to gradle file in dependency :
compile 'com.squareup.picasso:picasso:2.5.2'
After add this library, try loading image url like this.
Picasso.with(context).load("<Any Image URL>").into(imageView);
Hope it will help you !
Since you are alreadu using volley , no need to use Picasso.Volley provides you with a NetworkImageView.Simply replace your ImageView in xml with com.android.volley.toolbox.NetworkImageView and in code just use
NetworkImageView image = (NetworkImageView)findViewById(R.id.imageView);
image.setImageUrl("your url");

Is there any way to customize the names of the items in a listview?

I am making an mp3 playlist using listview which retrieves the path of all mp3 files stored in sd card and plays them on item click. But what I am getting is the paths of the files are displayed in the playlist, I want the names of the songs to be displayed instead of it. Is there any way to replace the item path by item name when the playlist is displayed? I need to access the file path so cannot add the names only to the list.
Here is my code:
package com.example.mp3;
import java.io.File;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> listAdapter ;
ArrayList<String> listTest;
ImageButton play,stop,back,next;
String songpath,song;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
listTest = new ArrayList<String>( );
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
Scanner("/sdcard/");////storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listTest);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id) //can two text be accessed here??
{
//accessing the song name
String name = (String) ((TextView) view).getText();
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(name);//source
mp.prepare();
mp.start();
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
mp.setDataSource(name);
Toast.makeText(MainActivity.this, "back", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
super.onPause();
mp.stop();
Toast.makeText(getApplicationContext(), "paused", Toast.LENGTH_LONG).show();
}
}
UPDATED
package com.example.mp3;
import java.io.File;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener, OnCompletionListener {
ListView list;
ArrayAdapter<String> listAdapter ;
ArrayList<String> listTest;
ArrayList<String> listSoundNames;
ImageButton play,stop,back,next;
String songpath,song;
File[] listFile;
SharedPreferences sharedPref;
MediaPlayer mp;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
song = sharedPref.getString("songname", "name");
mp=new MediaPlayer();
mp.setOnCompletionListener(this);
list = (ListView)findViewById(R.id.list);
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)findViewById(R.id.play);
back = (ImageButton)findViewById(R.id.prev);
next = (ImageButton)findViewById(R.id.next);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
//action bar controls
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
Scanner("/sdcard/");////storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
listAdapter = new ArrayAdapter<String> (MainActivity.this,R.layout.simplerow, listTest);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id) //can two text be accessed here??
{
//accessing the song name
String name = (String) ((TextView) view).getText();
//Log.e(TAG, name);
Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
mp.reset();
mp.setDataSource(listTest.get(position));//source
mp.prepare();
mp.start();
play.setImageResource(R.drawable.pause);
}
catch(Exception e){e.printStackTrace();}
}
});
}
}
////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////*Songs added here to list*////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp3"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(mp.isPlaying())
{
mp.pause();
Toast.makeText(MainActivity.this, "paused", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
mp.start();
Toast.makeText(MainActivity.this, "started", Toast.LENGTH_SHORT).show();
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
//mp.setDataSource(name);
Toast.makeText(MainActivity.this, "back", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
#Override
protected void onPause() {
super.onPause();
mp.stop();
Toast.makeText(getApplicationContext(), "paused", Toast.LENGTH_LONG).show();
}
}
what I am getting is the paths of the files are displayed in the
playlist
Because in listTest list adding path of file instead of sound file name.
Is there any way to replace the item path by item name when the
playlist is displayed?
Use separate ArrayList for storing file name at same time when adding file path in listTest :
ArrayList<String> listSoundNames;
listSoundNames=new ArrayList<String>();
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0) {
fileName = s.substring(0, pos);
}
listSoundNames.add(fileName);
Pass listSoundNames as data-source to ArrayAdapter and on click of ListView item use listTest ArrayList for getting file path to play:
mp.setDataSource(listTest.get(position));

Android: item list click on JSON generated list view - unable to click

I am getting a JSON from a url to generate a list view of contact names & numbers. I intend to make it where users can just tap on the contact name or phone to make a call directly. But I am having problem to get the tap on the item detected. I tried to put a log on the 'onItemClick' but it seems that it is not being called. Can you help see where I did wrong? Here is my code
package com.example.hk.sample;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class AllAccepted extends Activity {
ListView list;
TextView phone;
TextView name;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url;
//JSON Node Names
private static final String TAG_OS = "myjson";
private static final String TAG_VER = "phone";
private static final String TAG_NAME = "name";
JSONArray android = null;
//String matchId = Singleton.getInstance().getMatchIdString();
String matchId = "80";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_accepted);
list = (ListView) findViewById(R.id.listView1);
url = "http://demo.com/list.php?match_id="+ matchId;
Log.e("final view", "final layout array list");
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
final Button btnHistory = (Button) findViewById(R.id.goHome);
btnHistory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(myIntent);
}
});
}
protected void onItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
Log.e("item clicks", "selected: " + position);
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
phone = (TextView)findViewById(R.id.listPhone);
name = (TextView)findViewById(R.id.listName);
pDialog = new ProgressDialog(AllAccepted.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
oslist.add(map);
//list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(AllAccepted.this, oslist,
R.layout.all_accepted_layout,
new String[] { TAG_VER,TAG_NAME }, new int[] {
R.id.listPhone,R.id.listName});
list.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onBackPressed() {
}
}
Thanks in advance.
SOLUTION FOUND:
add this into onCreate method
list = (ListView) findViewById(R.id.listView1);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.e("item clicks", "selected: " + position);
String item = list.getItemAtPosition(position).toString();
String contactNum = ((TextView)view.findViewById(R.id.listPhone)).getText().toString();
Log.e("phone number", contactNum);
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse("tel:" + contactNum));
startActivity(intent);
}
});
thanks to Kunu for the help
Use this on your onCreate()
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
String contactNum = ((TextView)view.findViewById(R.id.listPhone)).getText().toString();
phoneCall(contactNum);
}
});
and don't forget to import import android.widget.AdapterView.OnItemClickListener;
After retrieving the number try this to make a call
public void phoneCall(String number)
{
String phoneCallUri = "tel:"+number;
Intent phoneCallIntent =new Intent(Intent.ACTION_CALL);
phoneCallIntent.setData(Uri.parse(phoneCallUri));
startActivity(phoneCallIntent);
}
to set the itemClickListener use :
listView.setOnItemClickListener(ActivityName.this);
Override the method, and also inside the xml
set the focusableInTouchMode to false, and also focusable to false for the textviews
Hope that helps
in OnCreate list.setOnItemClickListener(new OnItemClickListener() {});and then Add unimplement method
public class MainActivity extends Activity {
ListView lView ;
String[] ara={"a","b","c","d","e","f"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lView=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,ara);
lView.setAdapter(adapter);
lView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}});
}
}

Webview is blank or loading same page for different urls

A search api is returning me some meta data i.e a url "eventURL" and trackbackurl i.e "trackBack". I am placing the data in the listview, each row containing some data and a unique url and trackback url.When user taps on the row in the listview, a alert dialog is displayed presenting user 2 options. Clicking on option 1 should launch trackback url in a webview while clicking on second opion should launch eventURL in a webview.I have created a WebViewActivity for it,Problem is that my webview is always blank.
Main Activity
package my.stayactive.plan;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import my.stayactive.plan.ActiveHelper.ApiException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class StayActiveActivity extends Activity implements OnItemClickListener {
//private EditText m_search_text;
protected EditText m_zip;
private ListView m_search_results;
private Button m_search_btn;
private JSONArray m_results;
private LayoutInflater m_inflater;
private InputMethodManager m_ctrl;
private Spinner m_radius;
private Spinner m_activity_selector;
public static int radius = 0;
public static String activities;
public String url;
public String trackBack;
public static String assetId;
static final private int EXIT_ID = Menu.FIRST;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// m_search_text = (EditText) findViewById(R.id.search_text);
m_zip = (EditText) findViewById(R.id.zip);
m_search_btn = (Button) findViewById(R.id.search_button);
// m_searchm_results = (ListView) findViewById(R.id.lview);
m_search_btn .setOnClickListener(go_handler);
m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
m_inflater = LayoutInflater.from(this);
addListenerOnSpinnerItemSelection();
addListenerOnSpinner1ItemSelection();
m_search_results = (ListView)findViewById(R.id.lview);
m_search_results.setOnItemClickListener(this);
}
public void addListenerOnSpinnerItemSelection() {
m_radius = (Spinner) findViewById(R.id.spinner);
m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnSpinner1ItemSelection(){
m_activity_selector = (Spinner) findViewById(R.id.spinner1);
m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
super.onCreateOptionsMenu(menu);
menu.add(0, EXIT_ID, 0, R.string.exit);
return true;
}
#Override
public boolean onOptionsItemSelected (MenuItem item){
switch (item.getItemId()){
case EXIT_ID:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
OnClickListener go_handler = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);
//String searchText = Uri.encode(m_search_text.getText().toString());
String zip = Uri.encode(m_zip.getText().toString());
new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
// Show a toast showing the search text
Toast.makeText(getApplicationContext(),
getString(R.string.search_msg) + " " +
activities, Toast.LENGTH_LONG).show();
}
};
private class SearchTask extends AsyncTask<String, Integer, String>
{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
String result = ActiveHelper.download(params [0]);
return result;
} catch (ApiException e) {
e.printStackTrace();
Log.e("alatta", "Problem making search request");
}
return "";
}
#Override
protected void onPostExecute(String result) {
dialog.hide();
try {
JSONObject obj = new JSONObject(result);
m_results = obj.getJSONArray("_results");
if (m_results == null || m_results.length() == 0)
{
Toast.makeText(getApplicationContext(),
"No Results found for " + activities,
Toast.LENGTH_LONG).show();
}
else
m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private class JSONAdapter extends BaseAdapter
{
public JSONAdapter(Context c){
}
public int getCount()
{
return m_results.length();
}
public Object getItem(int arg0){
return null;
}
public long getItemId(int pos){
return pos;
}
public View getView(int pos, View convertView, ViewGroup parent) {
View tv;
TextView t;
if (convertView == null)
tv = m_inflater.inflate (R.layout.item, parent, false);
else
tv = convertView;
try {
/* For each entry in the ListView, we need to populate
* its text and timestamp */
t = (TextView) tv.findViewById(R.id.text);
JSONObject obj = m_results.getJSONObject(pos);
t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
//("\\<.*?\\>", ""))
t = (TextView) tv.findViewById(R.id.created_at);
JSONObject meta = obj.getJSONObject("meta");
// url = meta.getString("eventURL");
trackBack = obj.getString("url");
assetId = meta.getString("assetTypeId");
//String eventDate = meta.getString("startDate");
Calendar currentDate = Calendar.getInstance();
long dateNow = currentDate.getTimeInMillis();
String eventDate = meta.getString("startDate");
String endDate = meta.getString("endDate");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
Date date2 = null;
try {
date = formatter.parse(eventDate);
date2 = formatter.parse(endDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long modifiedDate= date.getTime();
long modifiedEndDate = date2.getTime();
if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)
{
t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
else {
t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
}
} catch (JSONException e) {
Log.e("alatta", e.getMessage());
}
return tv;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*try {
JSONObject obj = m_results.getJSONObject(position);
JSONObject meta = obj.getJSONObject("meta");
url = meta.getString("eventURL");
//Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
//StayActiveActivity.this.startActivity(intent);
} catch (JSONException e) {
Log.e("alatta",e.getMessage());
}*/
// TODO Auto-generated method stub
final CharSequence[] items = {"Register", "Additional Information"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Please Select an Option");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (which == 0){
Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
StayActiveActivity.this.startActivity(intent1);
}
else if ( which == 1){
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
StayActiveActivity.this.startActivity(intent);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}}
WebViewActivity
package my.stayactive.plan;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends StayActiveActivity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView);
WebSettings setting = webView.getSettings();
setting.setJavaScriptEnabled(true);
if (url != null && url.length()>0) {
webView.loadUrl(url);
}
}
}
You didn't pass URL to your WebViewActivity. To do that:
Before calling startActivity(), attach your URL to the intent with setData().
In onCreate() of WebViewActivity, retrieve the URL with getData(), then load it.
Or search for putExtra(...). You can transfer a number of data with Intent.
— edited —
Example:
To set data:
import android.net.Uri;
//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);
To retrieve data:
//...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
Uri uri = getIntent().getData();
//...
webView.loadUrl(uri.toString());
}
My guess is that your URLs are redirecting and that you aren't handling the redirects so nothing is being shown.
try adding this to your webview activity:
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return false;
}
});
Also it would be a good idea since you have an if statement in your WebView activity to log the url so that you can be certain that it is actually making it in to the activity correctly. If not the web view would never load anything.
EDIT: actually upon closer look it doesn't seem like you're setting the 'url' variable anywhere so it would be null, thus not calling your loadUrl method because of the if statement.

Categories

Resources