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:<|>|...|"|&|;|)(.|\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.
Related
I developed a word app that contains English vocabularies and users can add their favorite word by clicking on a floating button. Every time my favorite list has at list one item it is updated but when it's empty it doesn't show anything but when I run app again list updates.
if you need any code let me know to send it .
UPDATE:
Inner page :
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
Update 2:
package farmani.com.essentialwordsforielts.mainPage;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import farmani.com.essentialwordsforielts.R;
public class PageFragment extends Fragment {
private int mPage;
public static final String ARG_PAGE = "ARG_PAGE";
RecyclerView recyclerView;
AdapterFav adapterFav;
public static PageFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment fragment = new PageFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_page, container, false);
if (mPage == 1) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
AdapterList adapter = new AdapterList(MainActivity.context);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
if (mPage == 2) {
recyclerView = (RecyclerView) view.findViewById(R.id.my_recycler_view);
adapterFav = new AdapterFav(MainActivity.context);
recyclerView.setAdapter(adapterFav);
recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.context));
}
return view;
}
#Override
public void onResume() {
super.onResume();
if (adapterFav != null){
adapterFav.notifyDataSetChanged();
}
}
}
Update 3 :AdapterFav
package farmani.com.essentialwordsforielts.mainPage;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.innerpage.ActivityInnerPage;
public class AdapterFav extends RecyclerView.Adapter<ViewHolder> {
Context context;
LayoutInflater inflater;
TextView title;
ImageView avatar;
LinearLayout cardAdapter;
public AdapterFav(Context context){
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.adapter_card_view, parent, false);
title = (TextView) view.findViewById(R.id.title1);
avatar = (ImageView) view.findViewById(R.id.avatar);
cardAdapter = (LinearLayout) view.findViewById(R.id.card_adapter);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.title.setText(MainActivity.favorite.get(position).getWord());
String img = MainActivity.favorite.get(position).getImg();
int id = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
holder.avatar.setImageResource(id);
holder.cardAdapter.setOnClickListener(clickListener);
holder.cardAdapter.setId(position);
}
View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = view.getId();
Intent intent = new Intent (MainActivity.context, ActivityInnerPage.class);
intent.putExtra("name", "favorite");
intent.putExtra("id", position + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainActivity.context.startActivity(intent);
}
};
#Override
public int getItemCount() {
return MainActivity.favorite.size();
}
}
Update 4: MainActivity
package farmani.com.essentialwordsforielts.mainPage;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.nabinbhandari.android.permissions.PermissionHandler;
import com.nabinbhandari.android.permissions.Permissions;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.search.ActivitySearch;
import farmani.com.essentialwordsforielts.setting.ActivitySetting;
public class MainActivity extends AppCompatActivity {
public static Context context;
public static ArrayList<Structure> list = new ArrayList<>();
public static ArrayList<Structure> favorite = new ArrayList<>();
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView hamburger;
SQLiteDatabase database;
String destPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_activity_main);
Permissions.check(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
" storage permissions are required to copy database", new Permissions.Options()
.setSettingsDialogTitle("Warning!").setRationaleDialogTitle("Info"),
new PermissionHandler() {
#Override
public void onGranted() {
setupDB();
selectList();
selectFavorite();
}
});
context = getApplicationContext();
setTabOption();
drawerLayout = findViewById(R.id.navigation_drawer);
navigationView = findViewById(R.id.navigation_view);
hamburger = findViewById(R.id.hamburger);
hamburger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(Gravity.START);
}
});
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.exit) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.cancel();
}
});
alertDialog.show();
}else if (id == R.id.search) {
Intent intent = new Intent(MainActivity.this, ActivitySearch.class);
MainActivity.this.startActivity(intent);
} else if (id == R.id.setting) {
Intent intent = new Intent(MainActivity.this, ActivitySetting.class);
MainActivity.this.startActivity(intent);
}
return true;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.START);
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
alertDialog.setTitle(R.string.exit);
alertDialog.setMessage(R.string.exit_ask);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.setNegativeButton(R.string.no,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
}
private void setTabOption() {
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(new AdapterFragment(getSupportFragmentManager(),
context));
TabLayout tabStrip = findViewById(R.id.tabs);
tabStrip.setupWithViewPager(viewPager);
}
#Override
protected void onResume() {
super.onResume();
if (!list.isEmpty()){
list.clear();
selectList();
} if (!favorite.isEmpty()){
favorite.clear();
selectFavorite();
}
}
private void setupDB() {
try {
destPath =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
File file = new File(destPath);
if (!file.exists()) {
file.mkdirs();
file.createNewFile();
CopyDB(getBaseContext().getAssets().open("md_book.db"),
new FileOutputStream(destPath + "/md_book.db"));
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
private void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
private void selectFavorite() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE fav = 1",
null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
favorite.add(struct);
}
}
private void selectList() {
database = SQLiteDatabase.openOrCreateDatabase(destPath + "/md_book.db",
null);
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main", null);
while (cursor.moveToNext()) {
String word = cursor.getString(cursor.getColumnIndex("word"));
String definition =
cursor.getString(cursor.getColumnIndex("definition"));
String trans = cursor.getString(cursor.getColumnIndex("trans"));
String img = cursor.getString(cursor.getColumnIndex("img"));
int id = cursor.getInt(cursor.getColumnIndex("id"));
Structure struct = new Structure(word, definition, trans, img, id);
struct.setWord(word);
struct.setDefinition(definition);
struct.setTrans(trans);
struct.setImg(img);
struct.setId(id);
list.add(struct);
}
}
}
Update 5 innerpage activity
package farmani.com.essentialwordsforielts.innerpage;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.lang.reflect.Field;
import farmani.com.essentialwordsforielts.R;
import farmani.com.essentialwordsforielts.mainPage.AdapterFav;
public class ActivityInnerPage extends AppCompatActivity {
private TextView contentDescriptione;
private TextView moreDescriptione;
private ImageView avatar;
private ImageView imgCopy;
private ImageView imgShare;
private ImageView imgSms;
private ImageView imgGmail;
private FloatingActionButton favorite;
private CollapsingToolbarLayout collapsingToolbarLayout;
public String word;
public String definition;
public String trans;
public String img;
public int id;
private String destpath;
private SQLiteDatabase database;
private String favoriteState;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inner_page);
final android.support.v7.widget.Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
finish();
}
});
Bundle extras = getIntent().getExtras();
if (extras != null) {
int layoutId = Integer.parseInt(extras.getString("id"));
String pageName = extras.getString("name");
assert pageName != null;
if (pageName.equals("list")) {
id = MainActivity.list.get(layoutId).getId();
word = MainActivity.list.get(layoutId).getWord();
definition = MainActivity.list.get(layoutId).getDefinition();
trans = MainActivity.list.get(layoutId).getTrans();
img = MainActivity.list.get(layoutId).getImg();
} else if (pageName.equals("favorite")) {
id = MainActivity.favorite.get(layoutId).getId();
word = MainActivity.favorite.get(layoutId).getWord();
definition = MainActivity.favorite.get(layoutId).getDefinition();
trans = MainActivity.favorite.get(layoutId).getTrans();
img = MainActivity.favorite.get(layoutId).getImg();
}
}
contentDescriptione = findViewById(R.id.content_description);
moreDescriptione = findViewById(R.id.more_description);
imgCopy = findViewById(R.id.img_copy);
imgShare = findViewById(R.id.img_share);
imgSms = findViewById(R.id.img_sms);
imgGmail = findViewById(R.id.img_gmail);
avatar = findViewById(R.id.avatar);
favorite = findViewById(R.id.favorite);
collapsingToolbarLayout = findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.getExpandedTitleMarginStart();
collapsingToolbarLayout.setTitle(word);
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(android.R.color.holo_red_light));
contentDescriptione.setText(definition);
moreDescriptione.setText(trans);
int imgageId = MainActivity.context.getResources().getIdentifier(img, "drawable", MainActivity.context.getPackageName());
avatar.setImageResource(imgageId);
SharedPreferences prefes = getSharedPreferences("font_size", MODE_PRIVATE);
int value = prefes.getInt("fontsize", 16);
contentDescriptione.setTextSize(value);
moreDescriptione.setTextSize(value);
selectDb();
if(selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_like);
}else {
favorite.setImageResource(R.drawable.ic_favorite_maylike);
}
favorite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (selectFavoriteState()){
favorite.setImageResource(R.drawable.ic_favorite_maylike);
updateUnfavorited();
}else {
favorite.setImageResource(R.drawable.ic_favorite_like);
updateFavorited();
}
}
});
imgCopy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final ClipboardManager clipboardManager =
(ClipboardManager)ActivityInnerPage.this.getSystemService(Context.CLIPBOARD_SERVICE);
final ClipData clip = ClipData.newPlainText(word, trans+definition);
assert clipboardManager != null;
clipboardManager.setPrimaryClip(clip);
Snackbar.make(view,"متن کپی شد ",Snackbar.LENGTH_SHORT).show();
}
});
imgShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, definition+trans);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, word);
startActivity(Intent.createChooser(shareIntent, "Share"));
}
});
imgGmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent emailIntent = new Intent(Intent.ACTION_SENDTO
, Uri.fromParts("mailto", "", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, word);
emailIntent.putExtra(Intent.EXTRA_TEXT, definition);
startActivity(Intent.createChooser(emailIntent, "Send email..."));
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال ایمیل یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
imgSms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent sendSms = new Intent(Intent.ACTION_VIEW);
sendSms.putExtra("sms_body", definition + trans);
sendSms.setType("vnd.android-dir/mms-sms");
startActivity(sendSms);
}catch (Exception e){
Snackbar.make(view,"برنامه ای برای ارسال پیام یافت نشد",Snackbar.LENGTH_SHORT).show();
}
}
});
}
private void selectDb(){
destpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ielts/";
database = SQLiteDatabase.openOrCreateDatabase(destpath + "/md_book.db", null);
}
private boolean selectFavoriteState(){
#SuppressLint("Recycle") Cursor cursor = database.rawQuery("SELECT * FROM main WHERE id = " + id, null);
while (cursor.moveToNext()){
favoriteState = cursor.getString(cursor.getColumnIndex("fav"));
}
return favoriteState.equals("1");
}
private void updateFavorited(){
database.execSQL( "UPDATE main SET fav = 1 WHERE id = " + id);
}
private void updateUnfavorited(){
database.execSQL( "UPDATE main SET fav = 0 WHERE id = " + id);
}
}
In your FloatingActionButton onClick method after you save the new item in your database, insert your new item into your recyclerview datasource list and call notifyDatasetChanged() on the adapter.
Choice 1: in onResume() stub of MainActivity, call selectList() and selectFavorite() and then load the PageFragment again so that the new list is loaded properly.
This is the shortest wayout but this approach is very much unoptimized and is not recommended.
Choice 2: You will have to insert the new item in database as well as add it to the List and then call notifyDatasetChanged
In MainActivity within methods selectList() and selectFavorite() after you perform list.add(struct) and favourite.add(struct) respectively, you will have to call notifyDatasetChanged() for the Adapter.
But the problem is your RecyclerView is in the PageFragment whereas you're populating the list in MainActivity.
So move your selectList() and selectFavorite() to PageFragment where you first initialize the RecylerView then, set the Adapter and then populate the list and finally call notifyDatasetChanged() on your adapters.
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
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
}});
}
}
i have a registration app in the making where the user registers the data and on the other end the data can be shown and viewed and manipulated , i am using shared preferences method as shown below to write and access data (you can see them in DataEntry.java & DataManipulation.java shown below) but i want to use content provider method to manipulate data like quering or inserting or deleting....is there a way to do this and if yes can you please tell me how?
thank you
here are the codes below
the User end DataEntry.java:
package com.hossa.datamanipulation;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DataEntry extends Activity {
/*
* here is the part the user will submit several data for several people
*/
Button Submit, BroadcastButton;
TextView User, Email, Mobile;
EditText UserEdit, EmailEdit, MobileEdit;
String UserValue, EmailValue, MobileValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dataentry);
Submit = (Button) findViewById(R.id.DataSubmit);
BroadcastButton = (Button) findViewById(R.id.Broadcast);
User = (TextView) findViewById(R.id.TVuser);
Email = (TextView) findViewById(R.id.TVemail);
Mobile = (TextView) findViewById(R.id.TVmobile);
UserEdit = (EditText) findViewById(R.id.Edituser);
EmailEdit = (EditText) findViewById(R.id.Editemail);
MobileEdit = (EditText) findViewById(R.id.Editmobile);
Submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// saving the data of the user//
SharedPreferences sp = getSharedPreferences("userdata",
MODE_PRIVATE);// name of the file and it's mode//
SharedPreferences.Editor edit = sp.edit();// to be able to edit
// the file//
edit.putString("Username", UserEdit.getText().toString());// get
// the
// input
// username//
edit.putString("Email", EmailEdit.getText().toString());// get
// the
// input
// Email//
edit.putString("Mobile", MobileEdit.getText().toString());// get
// the
// input
// Mobile//
edit.commit();
Toast.makeText(getApplicationContext(),
"Data is Saved Successfully", Toast.LENGTH_SHORT)
.show();
}
});
BroadcastButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent e = new Intent();
e.setAction("com.hossa.data" + "manipulation.custombroadcast");
sendBroadcast(e);
}
});
}
#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;
}
}
and the other end DataManipulaton.java:
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class DataManipulation extends Activity {
Button ImportButton, ViewButton, RetrieveButton;
EditText UserShow;
TextView EmailDisplay, UserDisplay, MobileDisplay, EmailTV, UserTV,
MobileTV;
public static final String defaultvalue = "N/A";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datamanipulation);
ContentResolver ct = getContentResolver();
String Path = "data/data/com.hossa.datamanipulation/files/userdata";
Uri uri = Uri.parse("content://" + Path);
ImportButton = (Button) findViewById(R.id.ImportButton);
ViewButton = (Button) findViewById(R.id.ViewButton);
RetrieveButton = (Button) findViewById(R.id.RetrieveButton);
EmailDisplay = (TextView) findViewById(R.id.EmailDisplay);
MobileDisplay = (TextView) findViewById(R.id.MobileDisplay);
UserDisplay = (TextView) findViewById(R.id.UsernameDisplay);
EmailTV = (TextView) findViewById(R.id.EmailTV2);
UserTV = (TextView) findViewById(R.id.UserTV2);
MobileTV = (TextView) findViewById(R.id.MobileTV2);
final String U1[] = new String[10];
final String E1[] = new String[10];
final String M1[] = new String[10];
final String[][] alldata = new String[][] { U1, M1, E1 };
RetrieveButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int i = 0;
SharedPreferences spdata = getSharedPreferences("userdata",
Context.MODE_PRIVATE);
while (spdata.getString("Username", defaultvalue) != null) {
String tempuser = spdata
.getString("Username", defaultvalue);
U1[i] = tempuser;
i++;
}
i = 0;
while (spdata.getString("Email", defaultvalue) != null) {
String tempemail = spdata.getString("Email", defaultvalue);
E1[i] = tempemail;
i++;
}
i = 0;
while (spdata.getString("Mobile", defaultvalue) != null) {
String tempmobile = spdata
.getString("Mobile", defaultvalue);
M1[i] = tempmobile;
i++;
}
i = 0;
}
});
ImportButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getApplicationContext();
// TODO Auto-generated method stub
SharedPreferences sp = getSharedPreferences("userdata",
Context.MODE_PRIVATE);
String Username = sp.getString("Username", defaultvalue);
String Email = sp.getString("Email", defaultvalue);
String Mobile = sp.getString("Mobile", defaultvalue);
// what if there is no data from the user??//
if (Username.equals(defaultvalue) || Email.equals(defaultvalue)
|| Mobile.equals(defaultvalue)) {
Toast.makeText(getApplicationContext(),
"no data has been entered", Toast.LENGTH_SHORT)
.show();
} else {
UserTV.setText(Username);
EmailTV.setText(Email);
MobileTV.setText(Mobile);
}
}
});
//THE BELOW IS THE SECTION I NEED HELP WITH...THE ABOVE IS SIMPLY SOME TRIALS AND TESTS//
Cursor c = ct.query(uri, U1, null, null, null);
// c=ct.delete(uri, where, selectionArgs);
// c=ct.update(uri, values, where, selectionArgs);
}
#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;
}
}
PLEASE NOTE THAT BOTH CLASSES ARE IN THE SAME PACKAGE SO IT IS THE SAME APP NOT 2 DIFFERENT APPS
I am trying to do a simple APP that parses Currency data from Yahoo finance using their YQL query language. I tried parsing data with Google's finance API and it works fine but when I try it with Yahoo's URL it freezes before I even get to my parsing algorithm which is very strange.
package com.sfc.watcher;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Xml;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class ForexActivity extends Activity {
String temp1;
String temp2;
TableLayout tl1;
View temp3;
private static final String URL1 ="http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(\"" ;
private static final String URL2="\")&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
// This TAG is used for logging
private static final String TAG = "ForexWatcherActivity";
// These String constants refer to the XML elements we will be displaying
private static final String NAME = "Name";
private static final String RATE = "Rate";
private static final String DATE = "Date";
private static final String TIME = "Time";
private static final String ASK = "Ask";
private static final String BID = "Bid";
// This String refers to the attribute we are collecting for each element in
// our XML
private static final String DATA = "data";
// This HashMap will store, in key-value pairs, the currency data we receive.
private HashMap<String, String> hmCurrencyData = new HashMap<String, String>();
// This is the edit control that users will key into
private EditText edittext1 = null;
// This is the button that, when pressed, will request currency price data.
private Button button1 = null;
// This variable will hold the currency symbol value the user has keyed in.
private String symbol = "";
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
temp3=v;
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case R.id.edit:
return true;
case R.id.delete:
tl1.removeView(temp3);
return true;
case R.id.save:
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.forex);
tl1 = (TableLayout) findViewById(R.id.myTableLayout);
button1 = (Button)findViewById(R.id.bn_retrieve);
edittext1 = (EditText) findViewById(R.id.edit_symbol1);
edittext1.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) {
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
// here we respond to users key input events
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// collect the text from the edit control, and trim off spaces.
symbol = edittext1.getText().toString().trim();
// if the user has entered at least one character, enable the
// bnRetrieve button.
// otherwise, disable it.
button1.setEnabled(symbol.length() > 0);
}
});
final EditText edittext2 = (EditText) findViewById(R.id.edit_symbol2);
//First spinner for input forex
Spinner spinner1 = (Spinner) findViewById(R.id1.spinner);
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(
this, R.array.forex_array, android.R.layout.simple_spinner_item);
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
spinner1.setOnItemSelectedListener(new SellListener());
//Second spinner for Output forex
Spinner spinner2 = (Spinner) findViewById(R.id2.spinner);
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.forex_array, android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter2);
spinner2.setOnItemSelectedListener(new BuyListener());
// Capture our button from layout
Button button2 = (Button)findViewById(R.id.bn_convert);
// Register the onClick listener with the implementation above
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText( getApplicationContext(),"Selling "+ "$"+ edittext2.getText().toString()+ " "+ temp1 + " Buying "+ "$"+ temp2, Toast.LENGTH_LONG).show();
}
});
}
public class SellListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
temp1=parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public class BuyListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
temp2=parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public void retrieveQuote(View vw) {
// our "symbol" variable already has the text from the edSymbol view via
// the onTextChanged() event capture.
String request = URL1 + symbol + URL2;
CurrencyRetrieveTask task = new CurrencyRetrieveTask();
task.execute(new String[] { request });
}
private class CurrencyRetrieveTask extends AsyncTask<String, Void, String> {
private static final String TAG = "CurrencyRetrieveTask";
private ProgressDialog pDlg = null;
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
hideKeyboard();
pDlg = createProgressDialog(ForexActivity.this,
getString(R.string.retrieving));
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls) {
Log.i(TAG, "doInBackground");
StringBuilder sb = new StringBuilder();
// Remember that the array will only have one String
String url = urls[0];
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
sb.append(s);
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return sb.toString();
}
#Override
protected void onPostExecute(String response) {
readResponse(response);
displayResponse();
pDlg.dismiss();
}
}
private void hideKeyboard() {
// hide the soft keyboard, if it is currently visible.
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edittext1.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private ProgressDialog createProgressDialog(final Context context,
final String message) {
Log.i(TAG, "createProgressDialog");
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.setProgressDrawable(getWallpaper());
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
return progressDialog;
}
private void readResponse(String response) {
Log.i(TAG, "displayResponse");
// initialize our HashMap, resetting it if it was previously used.
hmCurrencyData = new HashMap<String, String>();
try {
String elementName = "";
String elementValue = "";
String nameSpace = "";
StringReader xmlReader = new StringReader(response);
XmlPullParser parser = Xml.newPullParser();
parser.setInput(xmlReader);
elementName = parser.getName();
while (!elementName.equals("rate"))
{
parser.nextTag();
elementName = parser.getName();
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private void updateTextView(String name, TableRow Row) {
if(hmCurrencyData.containsKey(name))
{
TextView TV1= new TextView(getApplicationContext());
TV1.setText(hmCurrencyData.containsKey(name) ? hmCurrencyData.get(name) : "");
TV1.setLayoutParams(new TableRow.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
Row.addView(TV1);
}
}
private void displayResponse() {
Log.i(TAG, "displayResponse");
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
tr.setPadding(0, 10, 0, 10);
updateTextView(NAME, tr);
updateTextView(RATE, tr);
updateTextView(DATE, tr);
updateTextView(TIME, tr);
updateTextView(ASK, tr);
updateTextView(BID, tr);
registerForContextMenu(tr);
tl1.addView(tr,new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
}
}
The table is not defined. The URL returns this error:
No definition found for Table yahoo.finance.xchange
When run in the browser:
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22%22%29&diagnostics=true