I'm trying to create an android widget containing a list of elements,but when drag the widget on home screen i get the message "loading" instead of the name of the item i want to display, What is the problem?
this is my list provider:
package com.example.noteskeeper;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService.RemoteViewsFactory;
import android.appwidget.AppWidgetManager;
public class ListProvider implements RemoteViewsFactory {
private Context context;
private int appWidgetId;
//private static final int mCount = 10;
//Context context
//private DBTools dbTools = new DBTools(context);
ArrayList<HashMap<String,String>> lists;
public ListProvider( Context context, Intent intent,ArrayList<HashMap<String,String>> listItems ){
this.context = context;
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
lists = listItems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return lists.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return Long.parseLong(lists.get(position).get("noteId"));
}
#Override
public RemoteViews getLoadingView() {
// TODO Auto-generated method stub
return null;
}
#Override
public RemoteViews getViewAt(int position) {
// TODO Auto-generated method stub
RemoteViews remoteView = new RemoteViews(
context.getPackageName(), R.layout.note_entry);
//HashMap<String,String> row = lists.get(position);
remoteView.setTextViewText(R.id.tvNoteId, lists.get(position).get("noteId"));
remoteView.setTextViewText(R.id.tvNoteTitle, lists.get(position).get("noteTitle"));
return remoteView;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
}
#Override
public void onDataSetChanged() {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
}
}
this is my service:
package com.example.noteskeeper;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
public class NotesWidgetService extends RemoteViewsService {
DBTools dbTools = new DBTools(this);
#Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
// TODO Auto-generated method stub
return (new ListProvider(this.getApplicationContext(), intent,
dbTools.getNotes()));
}
}
this is my provider:
package com.example.noteskeeper;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.ListAdapter;
import android.widget.RemoteViews;
import android.widget.SimpleAdapter;
public class NotesAppWidgetProvider extends AppWidgetProvider {
#SuppressWarnings("deprecation")
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
final int N = appWidgetIds.length;
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.note_widget);
for (int i=0; i<N; i++) {
Intent intent = new Intent(context, NotesEditor.class);
Intent intent2 = new Intent(context, NotesFirst.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 0, intent2, 0);
views.setOnClickPendingIntent(R.id.btn_wnew, pendingIntent);
views.setOnClickPendingIntent(R.id.textView1, pendingIntent2);
Intent svcIntent = new Intent(context, NotesWidgetService.class);
svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
svcIntent.setData(Uri.parse(
svcIntent.toUri(Intent.URI_INTENT_SCHEME)));
views.setRemoteAdapter(appWidgetIds[i],R.id.noteslist,
svcIntent);
views.setEmptyView(R.id.noteslist, R.id.empty_view);
appWidgetManager.updateAppWidget(appWidgetIds[i], views);
}
}
}
my xml files:
widget provider:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="250dip"
android:minHeight="110dip"
android:widgetCategory="home_screen|keyguard"
android:initialLayout="#layout/note_widget"
android:resizeMode="horizontal|vertical" android:updatePeriodMillis="1800000">
</appwidget-provider>
widget xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="35dp"
android:background="#color/white">
<TextView
android:id="#+id/textView1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="#string/app_name"
android:textColor="#color/white"
android:background="#color/black"
android:textAlignment="center"
android:gravity="center"
android:layout_marginRight="0.1dp"
/>
<Button
android:id="#+id/btn_wnew"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/as"
android:background="#color/black"
android:textSize="26sp"
style="?android:attr/borderlessButtonStyle"
android:textColor="#color/white"
/>
<TextView
android:id="#+id/empty_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="#string/empty_string"
android:textColor="#ffffff"
android:textSize="20sp"
android:visibility="gone" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list" >
<ListView
android:id="#+id/noteslist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="#android:style/TextAppearance.Medium"
>
</ListView>
</LinearLayout>
</LinearLayout>
</FrameLayout>
my element xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvNoteId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="#+id/tvNoteTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>
</TableRow>
</TableLayout>
Related
I have a splash screen and after that my main activity starts. This works fine in portrait mode but if in case i tilt my phone in landscape mode, the main activity can be seen launching more than once after splash screen.
I tried using android:launchMode="singleInstance" but in that case i am not able to attach files in feedback alert-box.
Following is my code:
MainActivity.java
package com.example.android.tel;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.Crashlytics;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
Toolbar mActionBarToolbar;
TextView toolbar_title_mainActivity, main_textView, disclaimer_txtView;
CardView SearchDept, SearchName, disclaimer, feedback;
ImageView back;
ArrayList<Uri> arrayUri = new ArrayList<Uri>();
ArrayAdapter<Uri> myFileListAdapter;
ListView listViewFiles;
Dialog alertDialog;
final int RQS_LOADIMAGE = 0;
final int RQS_SENDEMAIL = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_main);
} else {
setContentView(R.layout.activity_main);
}
mActionBarToolbar = (Toolbar) findViewById(R.id.tool_bar_main_activity);
toolbar_title_mainActivity = (TextView) findViewById(R.id.toolbar_title);
main_textView = (TextView) findViewById(R.id.main_textView);
main_textView.setPaintFlags(main_textView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar_title_mainActivity.setText("Hry. Govt. Telephone Directory");
back = (ImageView) findViewById(R.id.back);
back.setVisibility(View.INVISIBLE);
disclaimer = (CardView) findViewById(R.id.disclaimer);
feedback = (CardView) findViewById(R.id.feedback);
SearchDept = (CardView) findViewById(R.id.cardView1_mainActivity);
SearchName = (CardView) findViewById(R.id.cardView2_mainActivity);
SearchDept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, CardViewActivity.class);
startActivity(i);
}
});
SearchName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent j = new Intent(MainActivity.this, ByNameListActivity.class);
startActivity(j);
}
});
disclaimer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Dialog alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.disclaimer);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.show();
}
});
feedback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog = new Dialog(MainActivity.this);
alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
alertDialog.setContentView(R.layout.feedback);
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
alertDialog.setCanceledOnTouchOutside(true);
ImageView send_btn=(ImageView)alertDialog.findViewById(R.id.send);
ImageView attach_btn=(ImageView)alertDialog.findViewById(R.id.attachment);
final TextView to_email_add=(TextView)alertDialog.findViewById(R.id.email_address);
to_email_add.setText("tel#gmail.com");
final EditText email_subject=(EditText)alertDialog.findViewById(R.id.email_subject);
final EditText email_text=(EditText)alertDialog.findViewById(R.id.email_text);
final EditText mobile_no=(EditText)alertDialog.findViewById(R.id.mobile_text);
email_subject.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
email_text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
myFileListAdapter = new ArrayAdapter<Uri>(
MainActivity.this,
android.R.layout.simple_list_item_1,
arrayUri);
listViewFiles = (ListView)alertDialog.findViewById(R.id.filelist);
listViewFiles.setAdapter(myFileListAdapter);
listViewFiles.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
myFileListAdapter.remove(arrayUri.get(position));
myFileListAdapter.notifyDataSetChanged();
Toast.makeText(view.getContext(), "You unattached one item", Toast.LENGTH_LONG).show();
return false;
}
});
attach_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
send_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email_add=to_email_add.getText().toString();
String email_sub=email_subject.getText().toString();
String email_txt=email_text.getText().toString();
String emailAddressList[] = {email_add};
String mobileNo=mobile_no.getText().toString();
String info=email_txt+"\n\nPhone Number :"+mobileNo;
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_EMAIL, emailAddressList);
intent.putExtra(Intent.EXTRA_SUBJECT, email_sub);
intent.putExtra(Intent.EXTRA_TEXT,info);
if(arrayUri.isEmpty()&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email without photo attached
intent.setAction(Intent.ACTION_SEND);
intent.setType("plain/text");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size() == 1 && isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with ONE photo attached
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, arrayUri.get(0));
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}else if(arrayUri.size()>1&& isValidPhone(mobileNo)&& !(mobileNo.isEmpty())){
//send email with MULTI photo attached
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, arrayUri);
intent.setType("image/*");
new Handler().postDelayed(new Runnable() {
public void run() {
alertDialog.dismiss();
}
}, 5000);
}
else {
Toast.makeText(v.getContext(), "Phone number is not valid", Toast.LENGTH_LONG).show();
}
startActivity(Intent.createChooser(intent, "Please provide valid details"));
}
});
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
switch(requestCode){
case RQS_LOADIMAGE:
Uri imageUri = data.getData();
arrayUri.add(imageUri);
myFileListAdapter.notifyDataSetChanged();
break;
case RQS_SENDEMAIL:
break;
}
}
}
public static boolean isValidPhone(String phone)
{
String expression = "^([0-9\\+]|\\(\\d{1,3}\\))[0-9\\-\\. ]{3,15}$";
CharSequence inputString = phone;
Pattern pattern = Pattern.compile(expression);
Matcher matcher = pattern.matcher(inputString);
if (matcher.matches())
{
return true;
}
else{
return false;
}
}
public void hideKeyboard(View view) {
InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:weightSum="14"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
tools:context="com.example.android.tel.MainActivity">
<include
android:id="#+id/tool_bar_main_activity"
layout="#layout/toolbar">
</include>
<TextView
android:id="#+id/main_textView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5"
android:layout_marginTop="10dp"
android:text="How would you like to search?"
android:textStyle="bold"
android:textSize="14sp"
android:textColor="#1A237E"
android:gravity="center_horizontal"/>
<RelativeLayout
android:id="#+id/searchby_btns"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="4"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:gravity="center_vertical">
<android.support.v7.widget.CardView
android:id="#+id/cardView1_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="10dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Department.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/cardView2_mainActivity"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_gravity="center"
android:layout_below="#id/cardView1_mainActivity"
card_view:cardCornerRadius="4dp"
android:layout_marginTop="20dp"
card_view:cardBackgroundColor="#e97c1d">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search By Name.."
android:textColor="#android:color/white"
android:textStyle="bold"
android:textSize="18sp"
android:layout_centerInParent="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="8.5">
<ImageView
android:id="#+id/map_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="#drawable/hry_map"
android:elevation="4dp"
android:layout_gravity="center"/>
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/map_image"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingRight="16dp"
android:paddingLeft="16dp"
android:layout_marginTop="2dp"
android:gravity="center_horizontal"
android:layout_alignParentBottom="true">
<android.support.v7.widget.CardView
android:id="#+id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
android:layout_marginRight="8dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Disclaimer"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/feedback"
android:layout_toRightOf="#id/disclaimer"
android:layout_width="150dp"
android:layout_height="30dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardBackgroundColor="#424242">
<TextView
android:layout_width="150dp"
android:layout_height="30dp"
android:text="Feedback"
android:gravity="center"
android:layout_gravity="center_vertical"
android:textColor="#FFFFFF"
android:textStyle="bold"/>
</android.support.v7.widget.CardView>
</RelativeLayout>
</LinearLayout>
SplashScreenActivity.java
package com.example.android.telephonedirectory;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ProgressBar;
import com.felipecsl.gifimageview.library.GifImageView;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
public class SplashScreenActivity extends AppCompatActivity {
// private GifImageView gifimageview;
private ProgressBar progressBarSplashScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
setContentView(R.layout.activity_splash_screen);
} else {
setContentView(R.layout.activity_splash_screen);
}
// gifimageview=(GifImageView)findViewById(R.id.gifSplashscreenImage);
progressBarSplashScreen=(ProgressBar)findViewById(R.id.progressbarSplashscreen);
progressBarSplashScreen.setVisibility(progressBarSplashScreen.VISIBLE);
//set GifImageView Resource
/*try {
InputStream inputStream=getAssets().open("splash_Screen.png");
byte[] bytes= IOUtils.toByteArray(inputStream);
gifimageview.setBytes(bytes);
gifimageview.startAnimation();
}catch (IOException ex){
}*/
//Wait for 4 seconds and start activity main
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
SplashScreenActivity.this.startActivity(new Intent(SplashScreenActivity.this,MainActivity.class));
SplashScreenActivity.this.finish();
}
},2000);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation;
if (getResources().getConfiguration().orientation ==
Configuration.ORIENTATION_PORTRAIT) {
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
// or = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}else {
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
// Add code if needed
// listViewFiles.setAdapter(myFileListAdapter);
// myFileListAdapter.notifyDataSetChanged();
setRequestedOrientation(orientation);
}
}
Dont use android:launchMode="singleInstance"
Launch mode you should use "singleTask" for this .
Because singleInstance creates separate task stack for Activity and do not check activity in current Task Stack.
while "singleTask" check each time if an Activity exist in Task Stack it can not create new one.
I'm trying to create a list of Card view using a custom adapter. I have defined the layout of a single row of list, consisting a card view and imageview/textviews in it, in a separate .xml file. I'm using a custom srrsy adapter. My app crashes when I try to open the activity having list view , giving only an Runtime-exception error.
Error:
AndroidRuntime(2583): at graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter.getView(PostArrayAdapter.java:44)
This error is at the line
LayoutInflater li =(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
in custom adapter.
Here is single_card_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/ll1">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:id="#+id/ll2">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:id="#+id/imgIcon"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/ll3"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SampleTitle1"
android:layout_marginTop="10dp"
android:background="#00b5ad"
android:textSize="20dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/title"
android:textColor="#ffffff"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sampledisription1"
android:layout_marginTop="10dp"
android:background="#ffffff"
android:textSize="10dp"
android:gravity="center"
android:padding="5dp"
android:id="#+id/desciption"
/>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
Here is PostArrayAdapter.java
package graph.prathya.com.nextstepz.CustomAdapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import graph.prathya.com.nextstepz.R;
/**
* Created by Prathya on 5/23/2015.
*/
public class PostArrayAdapter extends ArrayAdapter<Post>{
Context context;
Post data[] =null;
int layoutid;
public PostArrayAdapter(Context context, int layoutid, Post data[]) {
super(context,layoutid);
this.data=data;
this.layoutid=layoutid;
}
private class PostHolder{
ImageView imgIcon;
TextView title,description;
}
#Override
public int getCount(){
return data.length;
}
#Override
public View getView(int Position, View convertView, ViewGroup parent){
PostHolder holder;
View v = convertView;
if(v==null){
LayoutInflater li = LayoutInflater.from(context);/* RunTimeExceptio error at this line of code */
v= li.inflate(layoutid,parent,false);
holder = new PostHolder();
holder.imgIcon = (ImageView)v.findViewById(R.id.imgIcon);
holder.title = (TextView)v.findViewById(R.id.title);
holder.description= (TextView)v.findViewById(R.id.desciption);
v.setTag(holder);
}
else {
holder = (PostHolder)v.getTag();
}
Post post = data[Position];
holder.imgIcon.setImageResource(post.imgIcon);
holder.title.setText(post.title);
holder.description.setText(post.description);
return v;
}
}
Here is activity in which listView lies: HomeScreenAvtivity.java
package graph.prathya.com.nextstepz;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ListView;
import graph.prathya.com.nextstepz.Communicator.Communicater1;
import graph.prathya.com.nextstepz.CustomAdapters.Post;
import graph.prathya.com.nextstepz.CustomAdapters.PostArrayAdapter;
public class HomeScreenActivity extends ActionBarActivity {
ImageButton passionbtn, eventbtn, projectbtn, groupstudybtn;
Dialog dg;
ListView listView = null;
Post post[] =new Post[] {
new Post(R.drawable.img1,"Cats and Children","Cats can be a fascinating experience for children, but young minds can sometimes confuse a pet for a toy. Teach children how to respect and properly handle your cat for best results."),
new Post(R.drawable.img2,"Android:The Best OS","Android powers hundreds of millions of mobile devices in more than 190 countries around the world.Android’s openness has made it a favorite for consumers."),
new Post(R.drawable.img3,"Beautiful","Monica is an Italian actor and model who started her modelling career at the age of 13 by posing for a local photo enthusiast."),
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView)findViewById(R.id.homelist);
listView.setAdapter(new PostArrayAdapter(getApplicationContext(),R.layout.single_card_view,post));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (item.getItemId() == R.id.nxtsignupitem) {
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.eventitem1) {
Intent in = new Intent(getApplicationContext(), PostDetailActivity.class);
startActivity(in);
}
if (item.getItemId() == R.id.postitem11) {
dg = new Dialog(HomeScreenActivity.this);
dg.requestWindowFeature(Window.FEATURE_NO_TITLE);
dg.setContentView(R.layout.fragment_new_post_dialogue);
dg.setTitle("Please choose One option");
dg.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dg.show();
passionbtn = (ImageButton) dg.findViewById(R.id.imageButton1st);
eventbtn = (ImageButton) dg.findViewById(R.id.imageButton2);
projectbtn = (ImageButton) dg.findViewById(R.id.imageButton3);
groupstudybtn = (ImageButton) dg.findViewById(R.id.imageButton4);
passionbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(1);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
eventbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(2);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
projectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(3);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
groupstudybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Communicater1.setpostButtonid(4);
Intent in = new Intent(getApplicationContext(), PostActivity.class);
startActivity(in);
}
});
}
return super.onOptionsItemSelected(item);}
#Override
public boolean onCreateOptionsMenu(Menu menu){
// TODO Auto-generated method stub
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.menu_home_screen, menu);
return super.onCreateOptionsMenu(menu);
} }
XML layout file of HomeScreenActivity
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/DrawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/lord"
android:layout_marginBottom="20dp"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/homelist">
</ListView>
</LinearLayout>
</ScrollView>
Post.java used in Adapter
package graph.prathya.com.nextstepz.CustomAdapters;
/**
* Created by Prathya on 5/23/2015.
*/
public class Post {
int imgIcon;
String title,description;
public Post(int imgIcon,String title, String description){
this.imgIcon=imgIcon;
this.title=title;
this.description=description;
}
}
you never assign context in your constructor.
add
this.context = context;
to your constructor
I want to remove any space between different items in a ListView.
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="#+id/wrapper"
android:padding="0dp"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/comment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:textColor="#000000"/>
</LinearLayout>
And Listview
<ListView
android:id="#+id/listView1"
android:transcriptMode="alwaysScroll"
android:stackFromBottom="true"
android:dividerHeight="0dp"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
But there is still some space between the items. Can anyone help me?
The line android:dividerHeight="10dp" causes the gaps between your lines. I color-coded the overall UI:
Once I set the dividerHeight line above from "10dp" to "0dp" I got this:
Ok, so here is the full set of code I used so you can see where you may have gone wrong.
MainActivity:
package com.ds.listviewtest;
import android.app.ListActivity;
import android.content.Context;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
public class MainActivity extends ListActivity {
static final String[] FRUITS = new String[] {
"Apple", "Avocado", "Banana",
"Blueberry", "Coconut", "Durian", "Guava", "Kiwifruit",
"Jackfruit", "Mango", "Olive", "Pear", "Sugar-apple"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new SimpleAdapter(FRUITS));
setContentView(R.layout.activity_main);
}
private class SimpleAdapter implements ListAdapter
{
String[] items;
public SimpleAdapter(String[] items)
{
this.items = items;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public void unregisterDataSetObserver(DataSetObserver observer) {
// TODO Auto-generated method stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return false;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_item, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.comment);
textView.setText(items[position]);
return rowView;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean areAllItemsEnabled() {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean isEnabled(int position) {
// TODO Auto-generated method stub
return true;
}
}
}
Here is list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#android:color/holo_orange_dark"
android:id="#+id/wrapper"
android:padding="0dp"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/comment"
android:background="#android:color/holo_blue_light"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:text="This is a test comment"
android:textColor="#000000"/>
</LinearLayout>
Finally here is activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/holo_red_light"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/holo_green_light"
android:dividerHeight="0dp" /> <!-- EDIT THIS VALUE HERE TO 0DP -->
</RelativeLayout>
Simply, give your divider height a negative value.
Example :
android:dividerHeight="-20dp"
This will remove spaces between ListView values.
So I'm trying to make two dialogs (dialogInfo & dialogGuide) in one class. One is for showing info about the app, another one for showing the guide how to use it. I can access both of them by click an image button (imbtnInfo & imbtnGuide) respectively on the main class (startover)
Info dialog works fine. But I can't achieve to use textview in Guide dialog so it becomes my problem now. I want to show a text file from /res/raw/legal.txt on Guide dialog (I created the raw folder)
My text file contains html codes too.
Here are my codes:
startover.java (the main class)
package com.fitria.MedicalRecord;
import com.fitria.cobalogin.R;
import android.content.Context;
import android.widget.ImageButton;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.text.Html;
import android.text.util.Linkify;
public class startover extends Activity
{
ImageButton imbtnInfo, imbtnGuide;
Button btnRecord, btnData, btnExit;
Dialog dialogInfo, dialogGuide;
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startover);
dialogInfo = new Dialog(this);
dialogInfo.setContentView(R.layout.info);
dialogInfo.setTitle("Info");
dialogInfo.setCancelable(true);
dialogGuide = new Dialog(Context);
dialogGuide.setContentView(R.layout.guide);
dialogGuide.setTitle("Guide");
dialogGuide.setCancelable(true);
txt = (TextView)findViewById(R.id.textbox);
imbtnInfo=(ImageButton)findViewById(R.id.imageInfo);
imbtnGuide=(ImageButton)findViewById(R.id.imageGuide);
btnRecord=(Button)findViewById(R.id.buttonRecord);
btnData=(Button)findViewById(R.id.buttonData);
btnExit=(Button)findViewById(R.id.buttonExit);
btnRecord.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),signup.class);
startActivity(intentSignUP);
}
});
btnData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),signup.class);
startActivity(intentSignUP);
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentHome=new Intent(getApplicationContext(),Home.class);
startActivity(intentHome);
}
});
imbtnInfo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialogInfo.show();
}
});
imbtnGuide.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
txt.setText(readRawTextFile(R.raw.legal));
dialogInfo.show();
}
});
}
}
info.xml (for dialogInfo)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/textbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Mobile Medical Record "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="20dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="1.0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Compatible with : Android 4.0.0 and up"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="fill"
android:text="Mobile Medical Record is an application supported by a hardware that able to display and save data of your heart and respiratory rate."
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Copyright © 2014"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/TextView02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="0dp"
android:text="Fitria Handayani"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="0dp"
android:text="All rights reserved."
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</ScrollView>
</LinearLayout>
guide.xml (for dialogGuide)
not the final layout but the final will look like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
<TextView
android:id="#+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="In order to operate this application and device you must sign up and fill information about yourself; name and age."
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/TextView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="fill"
android:text="There are two function in Mobile Medical Record, they are 'Record' and 'Data'. Record enables you to communicate with the hardware supporting this application so you will get results of your heart rate and respiratory measurement. Data enables you to save last 10 measurement of your heart rate and respiratory rate."
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Since I'm so new to Android app making (less than a week), please help me. Thanks in advance for anyone who tries to help me >.<
Edited :
Java codes edited based on Sagar's suggestion :
package com.fitria.MedicalRecord;
import com.fitria.cobalogin.R;
import android.content.Context;
import android.widget.ImageButton;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.text.Html;
import android.text.util.Linkify;
public class startover extends Activity
{
ImageButton imbtnInfo, imbtnGuide;
Button btnRecord, btnData, btnExit;
Dialog dialogInfo, dialogGuide;
TextView mtxt1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startover);
dialogInfo = new Dialog(this);
dialogInfo.setContentView(R.layout.info);
dialogInfo.setTitle("Info");
dialogInfo.setCancelable(true);
dialogGuide = new Dialog(this);
dialogGuide.setContentView(R.layout.guide);
dialogGuide.setTitle("Guide");
dialogGuide.setCancelable(true);
mtxt1 = (TextView)dialogGuide.findViewById(R.id.textbox);
mtxt1.settext(ImportTextFile());
imbtnInfo=(ImageButton)findViewById(R.id.imageInfo);
imbtnGuide=(ImageButton)findViewById(R.id.imageGuide);
btnRecord=(Button)findViewById(R.id.buttonRecord);
btnData=(Button)findViewById(R.id.buttonData);
btnExit=(Button)findViewById(R.id.buttonExit);
btnRecord.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),signup.class);
startActivity(intentSignUP);
}
});
btnData.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentSignUP=new Intent(getApplicationContext(),signup.class);
startActivity(intentSignUP);
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity and Start The Activity
Intent intentHome=new Intent(getApplicationContext(),Home.class);
startActivity(intentHome);
}
});
imbtnInfo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialogInfo.show();
}
});
imbtnGuide.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialogInfo.show();
}
});
}
String ImportTextFile()
{
String myText = "";
try
{
InputStream fileStream = getResources().openRawResource(R.raw.legal);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
}
catch (IOException e)
{
// exception handling
}
return myText;
}
}
I can't achieve to use textview in Guide dialog so it becomes my
problem now.
So here is your solution:
TextView mtxt1 = (TextView)dialogGuide.findViewById(R.id.textView1);
mtxt1.setText(ImportTextFile());
For reading Text from file:
String ImportTextFile()
{
String myText = "";
try {
InputStream fileStream = getResources().openRawResource(
R.raw.legal);
int fileLen = fileStream.available();
// Read the entire resource into a local byte buffer.
byte[] fileBuffer = new byte[fileLen];
fileStream.read(fileBuffer);
fileStream.close();
displayText = new String(fileBuffer);
} catch (IOException e) {
// exception handling
}
return myText;
}
I've been looking at this tutorial for how to use Spinners but I'm now stuck.
Currently when an item is selected from the spinner a toast is displayed with the choice, what I want to do instead is run a method to set the latitude and longitude to the selected country.
The button "Set Location to Japan" works perfectly by calling the method "SetLocationJapan". I just want take this process and put it into the spinner so whenever a choice is made the latitude and longitude is updated.
For example:
if Japan is selected in the spinner I want to call protected void setLocationJapan()
if France is selected I want to call protected void setLocationFrance()
if India is selected I want to call protected void setLocationIndia()
Code as requested:
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class SunriseSunset extends Activity implements OnClickListener {
public Button getLocation;
public Button setLocationJapan;
public TextView LongCoord;
public TextView LatCoord;
public double longitude;
public double latitude;
public LocationManager lm;
private Spinner spinner1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sunrisesunset);
addListenerOnSpinnerItemSelection();
findViewById(R.id.my_button).setOnClickListener(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1,
new MyLocationListener());
setLocationJapan = (Button) findViewById(R.id.SetLocationJapan);
getLocation = (Button) findViewById(R.id.GetLocation);
LongCoord = (TextView) findViewById(R.id.LongCoord);
LatCoord = (TextView) findViewById(R.id.LatCoord);
getLocation.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When GetLocation button is clicked the showCurrentLocation
// function is ran
showCurrentLocation();
}
});
setLocationJapan.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// When SetLocation button is clicked the setCurrentLocation
// function is ran
setLocationJapan();
}
});
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
protected void setLocationJapan() {
// TODO Auto-generated method stub
LatCoord.setText("35.4112");
LongCoord.setText("135.8337");
}
protected void setLocationFrance() {
// TODO Auto-generated method stub
LatCoord.setText("65.4112");
LongCoord.setText("85.8337");
}
protected void setLocationIndia() {
// TODO Auto-generated method stub
LatCoord.setText("21.4112");
LongCoord.setText("105.8337");
}
protected void showCurrentLocation() {
// TODO Auto-generated method stub
// This is called to find current location based on GPS data and sends
// this to LongCoord and LatCoord TextViewsw
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLatitude();
longitude = location.getLongitude();
LongCoord.setText(Double.toString(longitude));
LatCoord.setText(Double.toString(latitude));
}
#Override
public void onClick(View arg0) {
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
// Finds todays date and adds that into the URL
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd/MM");
String formattedDate = df.format(c.getTime());
String finalURL = "http://www.earthtools.org/sun/"
+ LatCoord.getText().toString().trim() + "/"
+ LongCoord.getText().toString().trim() + "/"
+ formattedDate + "/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(results));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
TextView tvSunrise = (TextView) findViewById(R.id.Sunrise);
TextView tvSunset = (TextView) findViewById(R.id.Sunset);
tvSunrise.setText(doc.getElementsByTagName("sunrise")
.item(0).getTextContent());
tvSunset.setText(doc.getElementsByTagName("sunset").item(0)
.getTextContent());
} catch (Exception e) {
e.printStackTrace();
}
}
Button b = (Button) findViewById(R.id.my_button);
b.setClickable(true);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
CustomOnItemSelectedListener.java
package richgrundy.learnphotography;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"You have changed to : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".SunriseSunset" >
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:entries="#array/country_arrays"
android:padding="10dp" />
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Date:"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Current Date"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
android:text="Location:"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<Button
android:id="#+id/GetLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Find Current Location" />
<Button
android:id="#+id/SetLocationJapan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Set Location to Japan" />
<LinearLayout
android:id="#+id/LinearLayout02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<TextView
android:id="#+id/LatCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
<TextView
android:id="#+id/LongCoord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" />
</LinearLayout>
<Button
android:id="#+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Calculate Sunrise/Sunset Time" />
<TextView
android:id="#+id/Sunrise"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/Sunset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00:00"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Any help would be hugely appreciated, Thanks!
I'm pretty sure I need to move setLocationJapan() etc. inside the CustomOnItemSelectedListener class but don't know how to proceed from there.
I'd prefer pseudo code answers so I can work this out for myself if possible :)
This is a bit dirty, but you can pass your activity to CustomOnSelectedListener and then call those methods using the activity. Example:
public class CustomOnSelectedListener extends implements OnItemSelectedListener {
Activity mActivity;
CustomOnSelectedListener(Activity mActivity) {
this.mActivity = mActivity;
}
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"You have changed to : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
if (mActivity instanceof SunriseSunset) {
SunriseSunset sunrise = (SunriseSunset) mActivity;
switch (pos) {
case 1: // Assuming Japan is first on your list
sunrise.setLocationJapan();
break;
... // fill in the rest here
}
}
}
... // rest of CustomOnSelectedListener here
}
However, this means all your setLocationJapan, setLocationIndia, etc. must change from protected to public so CustomOnSelectedListener can call them. Also, you must now instantiate CustomOnSelectedListener like this:
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener(this));