(Q) Load Custom system font from Extend TextView class. - Java for Android App Development

Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.

SpaceCaker said:
Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
Click to expand...
Click to collapse
i have fixed it.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
Typeface tf = Typeface.createFromFile("/system/fonts/Cooljazz.ttf");
profilename.setTypeface(tf);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}

Related

[Q] Please help with tutorial code!

Good evening everyone! I am working on learning some java and I have made it to the notepad tutorial and when I go to run it on the emulator, I am getting a few errors, and I'm hoping someone here may be able to help.
Code:
package com.a8a.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
//Inflat your view
setContentView(R.layout.main);
//Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
//Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
[B]aa = new ArayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);[/B] [I]Multiple markers at this line - ArayAdapter cannot be resolved to a type - Line breakpoint:ToDoList [line: 27] - onCreate[/I]
(Bundle)
//Bind the arary adapter to the listview.
myListView.setAdapter(aa);
[B]myEditText.setOnKeyListener(new OnKeyListener() {[/B] [I]OnKeyListener cannot be resolved to a type[/I]
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}
The bolded text is whats getting the error and the italics are the error itself. Any help would be appreciated, if you are able to explain why the change needs to be made as well that would be much appreciated, so I can learn from my mistakes.
Thanks in advance!
ArayAdapter was miss-spelled ArrayAdapter
I was also missing an import for OnKeyListener (import android.view.View.OnKeyListener). If you don't import a class and try to use it, Java doesn't know what it is, so it tells you it doesn't recognize the type.

ProgressDialog don't appear

Hy please help me!!
My full code:
Code:
package com.android.skiptvad;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.skiptvad.*;
public class Login extends Activity {
private static final int DIALOG_LOADING = 0;
/** Called when the activity is first created. */
TextView tvuser;
String sessionid;
ProgressDialog pd = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
tvuser = (TextView) findViewById(R.id.tvuser);
TextView tvpw = (TextView) findViewById(R.id.tvpw);
final EditText etuser = (EditText) findViewById(R.id.etuser);
final EditText etpw = (EditText) findViewById(R.id.etpw);
Button btlogin = (Button)findViewById(R.id.btlogin);
btlogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (etuser.getText() != null && etpw.getText()!= null)
{
pd = ProgressDialog.show(Login.this,"","Loading. Please wait...", true);
pd.show();
Thread t = new Thread() {
public void run(){
download(etuser.getText().toString(), md5(etpw.getText().toString()));
pd.dismiss();
}
};
t.run();
}
}
});
}
public void download (final String user, final String pw)
{
try{
HttpClient client = new DefaultHttpClient();
String postURL = "http://surfkid.redio.de/login";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pw));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
JSONObject menuObject = jObject.getJSONObject("responseData");
if (jObject.getInt("responseStatus")== 200 && jObject.get("responseDetails")!= null)
{
sessionid = menuObject.getString("session_id");
//dismissDialog(DIALOG_LOADING);
// pd.dismiss();
}
else
{
//dismissDialog(DIALOG_LOADING);
if (jObject.getInt("responseStatus")== 500)
{
throw new Exception("Server Error");
}
else if (jObject.getInt("responseStatus")== 400)
{
throw new Exception("Wrong User/Password");
}
else
{
throw new Exception();
}
}
//pd.dismiss();
} catch (Exception e) {
//dismissDialog(DIALOG_LOADING);
Toast toast ;
toast = Toast.makeText(getApplicationContext(), e.getMessage(), 500);
toast.show();
}
}
private String md5(String in) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
return null;
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_LOADING:
dialog = new ProgressDialog(this);
((ProgressDialog) dialog).setMessage("Loading, please wait...");
break;
}
return dialog;
}
}
My Problem is that the ProgressDialog don't appear.
Please help!!

How do I change text in card views list?

I'm trying to update the text in my card view. I cannot figure out how to do it. I posted the code of my recyclerAdapter class below.
When a user clicks a card view it should update the text on the card view with a specified time.
Code:
package com.teamtreehouse.oslist;
import java.util.ArrayList;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.net.Uri;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.util.Calendar;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class RecyclerAdapter extends RecyclerView.Adapter<FaucetHolder>
{
private ArrayList<Faucet> faucets;
private Context context;
private SharedPreferences sharedPref;
private String dateFormat = "h:mm a";
public RecyclerAdapter (ArrayList<Faucet> faucetsI,Context context) {
this.faucets = faucetsI;
this.context=context;
}
@Override
public FaucetHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view,viewGroup,false);
FaucetHolder f = new FaucetHolder(v);
return f;
}
@Override
public void onBindViewHolder(FaucetHolder f, int k)
{
final Faucet faucet = faucets.get(k);
f.titleText.setText(faucet.getName());
f.titleText.setOnClickListener(new View.OnClickListener() {
public void onClick(View btn) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(faucet.getLink()));
setRenewal(faucet);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount()
{
return faucets.size();
}
private void setRenewal(Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
SharedPreferences.Editor edit = sharedPref.edit();
Calendar c = Calendar.getInstance();
long current = c.getTimeInMillis();
long future = current + g.getLength();
c.setTimeInMillis(future);
SimpleDateFormat df = new SimpleDateFormat(dateFormat,Locale.US);
String date = df.format(c.getTime());
edit.putString(g.getSPName(),date);
}
private void updateText(FaucetHolder f, Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
String updatedTime = sharedPref.getString(g.getSPName(), null);
f.timeText.setText(updatedTime);
}
}
The full error text would be helpful. If you haven't done it before you can quickly check if something is wrong with your views in the adapter bei commenting them out.
Bump
Sent from my LG-F350K using Tapatalk

Custom List View Open New Activities

Hey everyone. Here is my code below. I have everything working. Got it to display the pictures and text in a list view. Only issue is that I want to be able to click on one of the list items and have it open an activity. When I added that part in, I get an error that states,
"Error44, 45) error: no suitable constructor found for Intent(<anonymous OnItemClickListener>,Class)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to Context)"
Here is my code:
Code:
package com.example.matt.nootropicahandbook;
import android.net.Uri;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
public class Biohack extends Activity
{
ListView list;
String[] itemname = {"Nootropics", "Supplements", "Metabolic Enhancement","Stacks", "Neuro Stimulation", "Diet", "Stay Away From",};
Integer[] imgid={R.drawable.piracetam1, R.drawable.piracetam2, R.drawable.piracetam3,
R.drawable.piracetam4, R.drawable.piracetam5, R.drawable.piracetam6, R.drawable.piracetam7,};
String[] classNames = {"Main", "Lifehack"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biohack);
biohacksAdapter adapter=new biohacksAdapter(this, itemname, imgid, classNames);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String openClass = classNames[position];
try{
Class selected = Class.forName("com.example.matt.nootropicahandbook."+openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
});
}
}
The error is on the line:
Code:
Intent selectedIntent = new Intent(this, selected);
And here is my adapter class for refrence
Code:
package com.example.matt.nootropicahandbook;
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;
public class biohacksAdapter extends ArrayAdapter<String>{
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
private final String[] classNames;
public biohacksAdapter(Activity context,String[] itemname, Integer[] imgid, String[] classNames) {
super(context,R.layout.custom_row, itemname);
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
this.classNames = classNames;
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.custom_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description "+itemname[position]);
return rowView;
}
}
replace
Intent selectedIntent = new Intent(this, selected);
to
Intent selectedIntent = new Intent(Biohack.this, selected);
because ...

[App]Notification notified on Emulator but not visible on Phone

Hi Everyone! I was working on an app, which needed to give a remainder on a certain time, by triggering a notification. The app seemed to work fine on the emulator. But, the notification never shows up on a real phone.
The service which sends the broadcast.
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by Tanmay on 22-01-2016.
*/
public class MyService extends IntentService {
public MyService() {
super("com.example.tanmay.yourdiary");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context context = this;
final Intent i = new Intent("com.example.tanmay.yourdiary.MyReceiver");
i.setAction("com.example.tanmay.yourdiary.MyReceiver");
new Thread(new Runnable(){
public void run(){
while(true){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String g="";
g=sdf.format(c.getTime());
Log.i("dd",g);
if(g.equals("05:23")){
Log.i("d3d",g);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
try {
Thread.sleep(24*60*60*1000);
stopSelf();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
The receiver
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("dfdfg", "bc rec");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Reminder").setContentText("Time to write your thoughts!");
TaskStackBuilder taskstackbuilder = TaskStackBuilder.create(context);
taskstackbuilder.addParentStack(MainActivity.class);
Intent i = new Intent(context,Writing.class);
taskstackbuilder.addNextIntent(i);
PendingIntent ip = taskstackbuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(ip);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
Try this code to see if it works on your phone or not
Code:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title").setContentText("Description text");
Intent resultIntent = new Intent(mContext, MainActivity.class);
resultIntent.putExtra(AN_ADITIONAL_EXTRA, "User clicked on the notification");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 10; // give it an ID you recognize within your application
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
And in your MainActivity.class under onNewIntent / onCreate
if(getIntent.getExtras() != null){
if(intent.hasExtra(AN_ADITIONAL_EXTRA)){
// User clicked on the notification, do something
}
}

Categories

Resources