android switch intent dynamically - java

I am trying to create a main menu activity in android which dynamically selects the activity destination from its position on the page.
MainMenu.java
package com.verscreative.BowlTrack;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class MainMenu extends SherlockActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
GridView gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new HomeMenuAdapter());
gridview.setPadding(50, 40, 50, 40);
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//Activities That are invoked by the click
String[] mActivitiesIds = {
getString(R.string.menu_launch_0),
getString(R.string.menu_launch_1),
getString(R.string.menu_launch_2),
getString(R.string.menu_launch_3),
getString(R.string.menu_launch_4),
getString(R.string.menu_launch_5)
};
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
//TODO: Switch Toast To Activity Intent
Intent i = new Intent();
i.setClassName(packageName, className);
try{
startActivity(i);
}catch(Exception e){
Toast t = Toast.makeText(getApplicationContext(), "Cannot Find Activity", Toast.LENGTH_LONG);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
activateSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void activateSettings(){
Intent i = new Intent(this, SettingsActivity.class);
startActivity(i);
}
public class HomeMenuAdapter extends BaseAdapter {
public HomeMenuAdapter() {
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
if (convertView == null) {
tv = new TextView(getApplicationContext());
tv.setGravity(Gravity.CENTER | Gravity.BOTTOM);
tv.setPadding(0, 10, 0, 10);
} else {
tv = (TextView) convertView;
}
tv.setCompoundDrawablesWithIntrinsicBounds(0, mThumbIds[position], 0, 0);
tv.setText(mTextIds[position]);
tv.setHeight(300);
tv.setTextColor(Color.WHITE);
return tv;
}
// references to our images
private Integer[] mThumbIds = {
android.R.drawable.ic_menu_add,
android.R.drawable.ic_menu_view,
android.R.drawable.ic_menu_info_details,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_close_clear_cancel,
android.R.drawable.ic_menu_preferences
};
private String[] mTextIds = {
getString(R.string.menu_item_0),
getString(R.string.menu_item_1),
getString(R.string.menu_item_2),
getString(R.string.menu_item_3),
getString(R.string.menu_item_4),
getString(R.string.menu_item_5)
};
}
}
However whatever I do it always says "Cannot Find Activity".
If I change:
String packageName = "com.verscreative.BowlTrack";
String className = mActivitiesIds[position]+".class";
Intent i = new Intent();
i.setClassName(packageName, className);
to for example:
Context packageName = MainMenu.this;
Class<ViewGamesActivity> className = ViewGamesActivity.class;
Intent i = new Intent();
i.setClass(packageName, className);
It works fine, but all options do the same thing!
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">BowlTrack</string>
<string name="action_settings">Settings</string>
<string name="menu_item_0">Add New Game</string>
<string name="menu_item_1">View Games</string>
<string name="menu_item_2">Stats</string>
<string name="menu_item_3">3-Not</string>
<string name="menu_item_4">4-Not</string>
<string name="menu_item_5">Settings</string>
<string name="menu_launch_0">NewGameActivity</string>
<string name="menu_launch_1">ViewGamesActivity</string>
<string name="menu_launch_2">ViewOverallActivity</string>
<string name="menu_launch_3">3-Not</string>
<string name="menu_launch_4">4-Not</string>
<string name="menu_launch_5">SettingsActivity</string>
<color name="black">#000000</color>
<color name="bwtk">#88078b</color>
<string name="title_activity_view_games">View Games</string>
</resources>
ViewGamesActivity.java
package com.verscreative.BowlTrack;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
public class ViewGamesActivity extends SherlockActivity {
public class ViewGames extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static final String url_all_products = "http://api.androidhive.info/android_connect/get_all_products.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_games);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid))
.getText().toString();
// TODO: Starting new intent
// Intent in = new Intent(getApplicationContext(),
// EditProductActivity.class);
// sending pid to next activity
// in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response
// back
// startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGamesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products,
"GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key =>
// value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// TODO: no products found
// Launch Add New product Activity
// Intent i = new Intent(getApplicationContext(),
// NewProductActivity.class);
// Closing all previous activities
// i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ViewGamesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME }, new int[] { R.id.pid,
R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
}

Thanks to jimpanzer and sherif-elkhatib, I have combined your comments to find the answer.
The Answer is Changing:
String className = mActivitiesIds[position]+".class";
to this:
String className = "com.verscreative.BowlTrack."+mActivitiesIds[position];

I don't think you need to specify the .class
Try this
String className = mActivitiesIds[position];
Otherwise, a more efficient solution would be to have a 2D array as such :
Object[][] mActivitiesIds =
{
{ getString(R.string.menu_launch_0), Activity1.class }
{ getString(R.string.menu_launch_1), Activity1.class }
{ getString(R.string.menu_launch_2), Activity1.class }
{ getString(R.string.menu_launch_3), Activity1.class }
{ getString(R.string.menu_launch_4), Activity1.class }
{ getString(R.string.menu_launch_5) Activity1.class }
};
Then simply use mActivitiesIds[n][1] to get the class...

Related

App crashing when attempting to add to ArrayAdapter

I am working on an assignment for school, the instructions are to create a Bookmark app with two activities, one named BookNote which must be a List Activity and another called ManageActivity.
BookNote is to populate the List Activity on startup with data read from a file, if no file is present an example bookmark is created. Bookmarks can be added, edited, and deleted, but all typing must be done in ManageActivity. Whenever Booknote handles the data returned from ManageActivity it should alter the list.
The code I have now has comments showing my intentions for each function, but my current problem is that everytime I return to BookNote from ManageActivity, the app crashes with the error "Attempt to invoke virtual method 'void android.widget.ArrayAdapter.insert(java.lang.Object, int)' on a null object reference" when attempting to add or insert a new bookmark object into the ArrayAdapter.
BookNote Activity
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class BookNote extends ListActivity{
private ArrayAdapter<Bookmark> adapter;
private final String FILENAME = "bookmarks.txt";
public String title = "EMPTY", url = "EMPTY", note = "EMPTY";
public String bookmarkClicked ="";
public int listViewID = 0;
public boolean intentListener = false;
public boolean addBookmarkClicked = false;
/*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity,
if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information
passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same
list element from which was chosen to edit.*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);
addBookmarkClicked = false;
intentListener = false;
intentListener = getIntent().getBooleanExtra("listen", false);
if(intentListener == true) {
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
title = getIntent().getExtras().getString("title");
url = getIntent().getExtras().getString("url");
note = getIntent().getExtras().getString("note");
listViewID = getIntent().getExtras().getInt("listViewID");
Bookmark bookmark = new Bookmark(title,url,note);
Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show();
if(addBookmarkClicked == true) {
addBookmark(bookmark);
}
else {
insertBookmark(bookmark, listViewID);
}
//writeData();
}
}
//When list item is clicked, fill bookmarkClicked with values in list item, record item position, and call gotoManageActivity() to pass information to ManageActivity.
public void onListItemClick(ListView listView, View view, int position, long id) {
ListView myListView = getListView();
Object itemClicked = myListView.getAdapter().getItem(position);
Toast.makeText(getApplicationContext(), "Item clicked: " + itemClicked + "\nItem ID: " + id,Toast.LENGTH_SHORT).show();
bookmarkClicked = itemClicked.toString();
listViewID = position;
gotoManageActivity();
}
//reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt
private ArrayList<Bookmark> readData(){
ArrayList<Bookmark> bookmarks = new ArrayList<>();
try {
FileInputStream fis = openFileInput(FILENAME);
Scanner scanner = new Scanner(fis);
if (scanner.hasNext()){
String titleScan = scanner.nextLine();
String urlScan = scanner.nextLine();
String noteScan = scanner.nextLine();
Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan);
bookmarks.add(bookmark);
}else{
Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note");
bookmarks.add(bookmark);
}
scanner.close();
} catch (FileNotFoundException e) {
}
return bookmarks;
}
//If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter.
private void addBookmark(Bookmark bookmark){
adapter.add(bookmark);
//writeData();
}
//If a list item is clicked, any edits will be inserted back into the ArrayAdapter in the same position of the item clicked.
private void insertBookmark(Bookmark bookmark, int listViewID){
adapter.insert(bookmark,listViewID);
//writeData();
}
//Calls ManageActivity and reports information about app.
public void gotoManageActivity(){
Intent manageIntent = new Intent(this, ManageActivity.class);
Bundle extras = new Bundle();
extras.putString("bookmark", bookmarkClicked);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
extras.putInt("listViewID", listViewID);
manageIntent.putExtras(extras);
startActivity(manageIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_book_note, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_add) {
addBookmarkClicked = true;
gotoManageActivity();
return true;
}
return super.onOptionsItemSelected(item);
}
}
ManageActivity
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class ManageActivity extends AppCompatActivity {
private String title = "EMPTY", url = "EMPTY", note = "EMPTY";
private boolean listener = true;
private boolean addBookmarkClicked = false;
/* When activity starts, check for addBookmarkClicked status, create book */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_layout);
addBookmarkClicked = getIntent().getBooleanExtra("addClicked", false);
String bookmarkString = "";
bookmarkString = getIntent().getExtras().getString("bookmark");
if(bookmarkString != null && bookmarkString.length() > 0) {
if (bookmarkString.length() != 0) {
String[] stringArray = bookmarkString.split("\\n");
title = stringArray[0];
url = stringArray[1];
note = stringArray[2];
updateTextViews();
}
}
else {
updateTextViews();
}
}
#Override
public void onBackPressed(){
Intent bookNoteIntent = new Intent(this, BookNote.class);
startActivity(bookNoteIntent);
Bundle extras = new Bundle();
extras.putString("title", title);
extras.putString("url", url);
extras.putString("note", note);
extras.putBoolean("listen", listener);
extras.putBoolean("addBookmarkClicked", addBookmarkClicked);
bookNoteIntent.putExtras(extras);
startActivity(bookNoteIntent);
}
public void editButtonCall(View view){
showNoteDialog();
showURLDialog();
showTitleDialog();
}
public void webButton(View view){
if(url.length() != 0 && url != "EMPTY"){
}
}
public void updateTextViews(){
TextView titleTextView = (TextView) findViewById(R.id.titleTV);
TextView urlTextView = (TextView) findViewById(R.id.urlTV);
TextView noteTextView = (TextView) findViewById(R.id.noteTV);
titleTextView.setText("Title: " + title);
urlTextView.setText("URL: " + url);
noteTextView.setText("Note: " + note);
}
//Show dialog and editText for user to assign title to bookmark.
public void showTitleDialog(){
AlertDialog.Builder titleBuilder = new AlertDialog.Builder(this);
titleBuilder.setTitle("Enter Title");
final EditText titleET = new EditText(this);
titleET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
titleBuilder.setView(titleET);
titleBuilder.setPositiveButton("Add", newDialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
title = titleET.getText().toString();
updateTextViews();
}
});
titleBuilder.show();
}
//Show dialog and editText for user to assign note to bookmark.
public void showNoteDialog(){
AlertDialog.Builder noteBuilder = new AlertDialog.Builder(this);
noteBuilder.setTitle("Enter Note");
final EditText noteET = new EditText(this);
noteET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
noteBuilder.setView(noteET);
noteBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
note = noteET.getText().toString();
updateTextViews();
}
});
noteBuilder.show();
}
//Show dialog and editText for user to assign url to bookmark.
public void showURLDialog(){
AlertDialog.Builder urlBuilder = new AlertDialog.Builder(this);
urlBuilder.setTitle("Enter URL");
final EditText urlET = new EditText(this);
urlET.setInputType(InputType.TYPE_TEXT_VARIATION_NORMAL);
urlBuilder.setView(urlET);
urlBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
url = urlET.getText().toString();
updateTextViews();
}
});
urlBuilder.show();
}
}
You are declaring a global and a local instance of adapter. In onCreate() method of BookNote Activity, remove the local instance. Change
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
to
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
You are not setting xml file which contains
book_layout.xml
<ListView android:id="#+id/android:list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.book_layout);
ArrayList<Bookmark> bookmarkList = readData();
ArrayAdapter adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList);
setListAdapter(adapter);

Load image in listview

I have an application which uses json to get links and texts and now i want to load the image from the downloaded url (by json) in the Listview.
I can load texts in the listview but i can load images!
PLZ help me i have spended 2 days for this and searched,... but no chance! I really need your help! anyone can help me i'll make a great thanks to him in application. PLZZZ help me.
MY CODE :
package rappage.rapfarsi.media.appteam.rapnews;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import rappage.rapfarsi.media.appteam.Articlectivity;
import rappage.rapfarsi.media.appteam.Main;
import rappage.rapfarsi.media.appteam.R;
import rappage.rapfarsi.media.appteam.json.JSONParser;
public class tab2 extends ListFragment {
static final String url_all_products = "http://normaluse.persianrapapp021.ml/article/get_all_products.php";
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
final String TAG_SUCCESS = "success";
final String TAG_RAPNEWS = "article";
final String TAG_PID = "pid";
final String TAG_TITLE = "title";
final String TAG_PIC = "pic";
final String TAG_WRITER = "writer";
Bitmap bmp;
// JSON Node names
// products JSONArray
JSONArray rapnews = null;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_2, container, false);
final View rootView = super.onCreateView(inflater, container, savedInstanceState);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
/**
* Background Async Task to Load all product by making HTTP Request
* */
try {
new LoadAllProducts().execute();
}catch (Exception e)
{
final AlertDialog.Builder dlgAlert = new AlertDialog.Builder(getActivity());
dlgAlert.setMessage("لطفا اینترنت خودرا چک کنید! یا ممکن است سرور از دسترس خارج شده باشد ، برای اخبار اپدیت و مشکلات به ویکی رپ مراجعه کنید!");
dlgAlert.setTitle("Connection Error!");
dlgAlert.setNegativeButton("باشه گرفتم", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(getActivity() , Main.class));
}
});
dlgAlert.create().show();
}
return v;
}
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading, Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
rapnews = json.getJSONArray(TAG_RAPNEWS);
// looping through All Products
for (int i = 0; i < 11; i++) {
JSONObject c = rapnews.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_TITLE);
String pic = c.getString(TAG_PIC);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_TITLE, name);
map.put(TAG_PIC, pic);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getActivity().getApplicationContext(),
Main.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
getActivity(), productsList,
R.layout.list_item, new String[]{TAG_PID,
TAG_TITLE},
new int[]{R.id.pid, R.id.txttitle}
);
setListAdapter(adapter);
}
});
}
}
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity().getApplicationContext(), "Loading, Please Wait...",
Toast.LENGTH_LONG).show();
String pid = ((TextView) v.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getActivity(),Articlectivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivity(in);
}
}
I WANT TO LOAD IMAGES ATLEAST IN THIS BASE... OR ANYOTHER THING...
There are lots of image loading library available for android.
Have a look at these
https://github.com/square/picasso
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading
https://android.googlesource.com/platform/frameworks/volley
https://github.com/koush/UrlImageViewHelper
https://github.com/novoda/image-loader
You can use library by square called Picasso
Here is the documentation.
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Here is a custom adapter for a listview having 2 texts and an image
public class CustomArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values1;
private final String[] values2;
public CustomArrayAdapter(Context context, String[] values1, String[] values2) {
super(context, R.layout.some_layout, values1);
this.context = context;
this.values1 = values1;
this.values2 = values2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// LayoutInflater inflater = LayoutInflater.from(context);
// View rowView = inflater.inflate(R.layout.some_layout, null);
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
rowView = inflater.inflate(R.layout.some_layout, null);
holder = new ViewHolder();
holder.text1 = (TextView) rowView.findViewById(R.id.firstLine);
holder.text2 = (TextView) rowView.findViewById(R.id.secondLine);
holder.img = (ImageView) rowView.findViewById(R.id.imageView);
rowView.setTag(holder);
}
else {
holder=(ViewHolder)rowView.getTag();
}
holder.text1.setText(values1[position]);
holder.text2.setText(values2[position]);
Picasso.with(rowView.getContext()).load("http://www.9ori.com/store/media/images/8ab579a656.jpg").into(holder.img);
// if (position%2==0) {
// holder.img.setImageResource(R.drawable.correct);
// }
// else {
// holder.img.setImageResource(R.drawable.incorrect);
// }
return rowView;
}
public static class ViewHolder {
public TextView text1, text2;
public ImageView img;
}
}

Method OnItemClickListener from JSONParser override OnItemLongClickListener from another activity

I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works

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