Hi all, im having a go at developing a simple app. i have little experience with Java and Android development. i have a little test app at the moment and have created a new class, im trying to create a new instance of this class on a button click. it fails to do so, i cant for the life of me see why so.. can someone shed any light on this?
Thanks
Debuging this shows it hitting the "LocationFactory locationf = new LocationFactory();" line and throwing an exception-
"java.lang.NullPointerException"
Main
Code:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends Activity {
private static final Context Context = null;
protected static final String TAG = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
[user=439709]@override[/user]
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;
}
public void mainButton(View view) throws IOException {
try {
LocationFactory locationf = new LocationFactory();
Toast.makeText(this, locationf.getAddress(),Toast.LENGTH_LONG).show();
} catch (Exception e)
{
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Class
Code:
package com.example.testapp;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import java.io.IOException;
import java.util.Locale;
import java.util.List;
public class LocationFactory
{
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory()
{
}
public String getAddress() throws IOException
{
String ReturnAddress = "";
String Address = "", City = "", Country = "";
List<Address> addresses = null;
if(manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
// Use GPS Radio Location
Location GPSlocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Latitude = GPSlocation.getLatitude();
Longitude = GPSlocation.getLongitude();
}
else
{
// Use Cell Tower Location
Location NETlocation = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Latitude = NETlocation.getLatitude();
Longitude = NETlocation.getLongitude();
}
if(Latitude > 0 && Longitude > 0)
{
addresses = geocoder.getFromLocation(Latitude, Longitude, 1);
if(!addresses.isEmpty())
{
Address = addresses.get(0).getAddressLine(0);
City = addresses.get(0).getAddressLine(1);
Country = addresses.get(0).getAddressLine(2);
}
}
ReturnAddress = Address + " " + City + " " + Country;
return ReturnAddress;
}
}
I don't see anywhere in your code where you are calling the mainButton(View view) method. In the Android lifecycle, the onCreate method is the equivalent of a normal Java program's main() method, which means that code execution begins with the first line of onCreate(). Not knowing what you're trying to do, a good start would be to call your mainButton() method AFTER setContentView() in onCreate().
Side note: your mainButton() method has a View parameter that is never used. Is there a reason for that?
Android activity lifecycle: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
e.g
Code:
Button button = (Button) findViewById(R.id.[B]button[/B]) // replace latter button with actual id defined in main xml.
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("[B]com.example.packagename.CLASSNAME[/B]")); // this should be your own package name.
}
});
Also define this in android manifest under the <application> and </application>
Code:
<activity
android:name=".[B]CLASSNAME[/B]"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="[B]com.example.packagename.CLASSNAME[/B]" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Change the values of BOLD text according to your own values.
I tried to help you as far as I understood your question. Please let me know if you face any problem I would be more than happy to help you. Rest I am also in the learning phase so you can always PM me if you face any problem.
Hit thanks if I have helped you in any way.
coolbud012 said:
You have to use an intent on that button click, use the method onClickListener and define the intent in the androidmanifest.xml
Click to expand...
Click to collapse
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
jpepin said:
Nope! He didn't say that he wanted to launch a new Activity when the button is clicked. He wants to create a new instance of his LocationFactory Class.
Click to expand...
Click to collapse
Oops yeah right read that now...I thought he want to start an activity... Anyways tried to delete my reply but not getting an option to delete.
There are many flaws in his code. And the other thing is if its his first app and if he has low level of programming experience then according to me it would be a next to impossible app for him, as per his code and what he is trying to implement.
I think he should rather start up with small apps, understand things and then move on to complex apps.
P.S - its just my opinion
Click to expand...
Click to collapse
Agreed that he should start small...which is exactly why your suggestion for creating and handling Intents makes no sense. Before that, he should first understand the activity lifecycle. Until then, he can just stick to trivial single-activity apps to gain experience.
OP: This code should be placed in the onCreate method:
Code:
Button button = (Button) findViewById(R.id.your_button_ID_here)
button.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
mainButton(); // get rid of the View parameter in this method...it's not needed
}
});
This will cause a new instance of your LocationFactory to be created, and will also cause your Toast message to be displayed.
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
osmorgan said:
thanks for the replies. yes you are right in that i am inexperienced, but this is just a test app for me to play around with and learn on. i tend to learn better by doing rather than constantly reading. thanks for your suggestions ill look into them
Click to expand...
Click to collapse
I also believe in the same, I also keep on doing experiments and testing things out.
What I would suggest is that start with a small app and understand the insights on how android works and all...
Thanks
Potential Solution
Alright, I think I've found your problem. Have a look at where you define your variables in your LocationManager class:
Code:
private static final Context Context = null;
Geocoder geocoder = new Geocoder(Context, Locale.getDefault());
LocationManager manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
This is your problem:
Code:
Context Context = null;
If your context is null, and you use it to create a geocoder and call Context.getSystemService, you'll hit a null pointer. You're trying to access an object (the Context) that doesn't even exist
I'd recommend you pass the context in the LocationManager constructor and then instantiate your objects there. That's standard java procedure.
Code:
private Context mContext = null;
Geocoder geocoder = null;
LocationManager manager = null;
public double Latitude = 0.0;
public double Longitude = 0.0;
public LocationFactory(Context context)
{
this.mContext = context;
this.geocoder = new Geocoder(context, Locale.getDefault());
this.manager = (LocationManager) Context.getSystemService(android.content.Context.LOCATION_SERVICE);
}
I also renamed Context to mContext - it's generally a good idea to keep the instance's name separate from the class name.
Try that - it should work. Please feel free to ask any more questions - this is how I learned, and I think it's the best way!
Related
ive been enamored by some of the more simple text based widgets as of late (like simplistic text and clockr) and decided to try to make a widget based on that design for gmail. it will display who the email is from in a text cloud where the most recent email is the largest with each subsequent email getting smaller. if the email is unread it will be bold, if not then it will be regular text.
my background is in making java apps for the command line and of a more linear layout. so i am learning android dev as i go. because i am learning as i go i am starting at the most basic and moving on. i have a widget with a text box that displays '0'. (yay! i know impressive). now i want to make the text increment by 1 every 1 second. (yes not very useful, but very useful for learning.) i want to do this with an AlarmManager. does the AlarmManager have to be in a service, or an adjacent activity, or could there be a static AlarmManager in my AppWidgetProvider class? i found some examples but they are all pretty complex. i want to start super simple and move towards advanced.
after that then i will do the same increment except each number will be added as a new textbox and the previous will decrease in size. and so on and so on.
any help would be greatly appreciated.
-Tyler
so i understand that a Handler is better for these small tics of times but doing this project is a learning excersise. let me show you what i have so far.
AndroidManifest.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tsb.gmailinboxtextcloud"
android:versionCode="1"
android:versionName="1.0">
<application android:label="GmailInboxTextCloud" android:icon="@drawable/gitc_icon">
<!-- Broadcast Receiver that will process AppWidget updates -->
<receiver android:name=".GITextCloud" android:label="@string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<!--
<intent-filter>
<action android:name="INCREMENT_COUNT_UPDATE" />
<action android:name="RESET_COUNT_UPDATE" />
<action android:name="PAUSE_COUNT_UPDATE"/>
</intent-filter>
-->
<meta-data android:name="android.appwidget.provider" android:resource="@xml/gitc_widget"/>
</receiver>
</application>
<service android:enabled="true" android:name=".AlarmService" />
</manifest>
my widget class
GITextCloud.java
Code:
package com.tsb.gmailinboxtextcloud;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GITextCloud extends AppWidgetProvider {
private int count = 0;
@Override
public void onEnabled(Context context) {
//super.onEnabled(context);
count = 0;
context.startService(new Intent(context, AlarmService.class));
Toast.makeText(context, "onEnabled() finished", Toast.LENGTH_LONG).show();
}
@Override
public void onDisabled(Context context) {
//super.onDisabled(context);
count = 0;
context.stopService(new Intent(context, AlarmService.class));
Toast.makeText(context, "onDisabled() finished", Toast.LENGTH_LONG).show();
}
@Override
public void onReceive(Context context, Intent intent) {
//super.onReceive(context, intent);
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.widget_textview, "[" + count + "]");
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName cName = new ComponentName(context, GITextCloud.class);
manager.updateAppWidget(cName, rv);
count++;
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
}
}
my service that runs an AlarmManager
AlarmService.java
Code:
package com.tsb.gmailinboxtextcloud;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
/**
* Created by IntelliJ IDEA.
* User: Tyler
* Date: 4/16/11
* Time: 6:34 PM
*/
public class AlarmService extends Service {
private AlarmManager am;
private PendingIntent pendingIntent;
// public static String INCREMENT_COUNT_UPDATE = "INCREMENT_COUNT_UPDATE";
// public static String RESET_COUNT_UPDATE = "RESET_COUNT_UPDATE";
// public static String PAUSE_COUNT_UPDATE = "PAUSE_COUNT_UPDATE";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
am.cancel(pendingIntent);
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
setRepeatingAlarm(GITextCloud.class);
}
public void setOneTimeAlarm(java.lang.Class<?> cls) {
Intent intent = new Intent(this, cls);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (5 * 1000), pendingIntent);
}
public void setRepeatingAlarm(java.lang.Class<?> cls) {
Intent intent = new Intent(this, cls);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (5 * 1000), pendingIntent);
}
}
what ends up happening is that my widget just shows [0] in white and 60sp big. never changes. and my toasts in the service never show up on the screen. am i starting the service wrong?
Is this just a stupid question or does no one know the answer? Cause if no one knows then nvm, wrong place to ask...
Its from my damn phone!!!
I haven't messed too much with app widgets, but don't you have to set some sort of refresh time in your metadata?
http://developer.android.com/guide/topics/appwidgets/index.html
Gene Poole said:
I haven't messed too much with app widgets, but don't you have to set some sort of refresh time in your metadata?
http://developer.android.com/guide/topics/appwidgets/index.html
Click to expand...
Click to collapse
yep, that determines how often the ACTION_APPWIDGET_UPDATE intent gets sent.
my gitc_widget.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:minWidth="146dip"
android:minHeight="72dip"
android:updatePeriodMillis="1000"
android:initialLayout="@layout/main">
</appwidget-provider>
buuut. after android 1.6 or maybe 1.5 that android:updatePeriodMillis tag defaults to 30minutes. which is why an AlarmManager must be used for anything less than 30min updates. and since i dont want to wait 30mins to know if my code works i need my service to start.
i have determined that my service never starts. it isnt shown in the running services on my android phone and the toasts from it never show. anyone know why the service isnt started?
As mentioned earlier, I don't know a lot about appwidgets, but they are incredibly difficult to debug and I've had to reboot the phone at times to get past bugs in my code, so don't be so sure that your service isn't running. First, I don't think AppServices show up in the "running services" tab, and second, I don't think toasts from a non-activity show up on the screen. I could be wrong about this, so don't take it as gospel. Try using Log() instead of Toast for debugging.
Also, I don't see anything in your code that sends an update to the appwidget. I think something in your service should eventually call GITextCloud.updateAppWidget().
Thanks for working with me. In my AlarmService class in the onStarted method i call the setRepeating() method that gets passed a class with wich it makes an intent that the AlarmManager should use to trigger the onRecieve() method in my GITextCloud class. I will look into the log(), thats a good idea. And i will be trying to setAction() on that intent and then specifically catch it in the onRecieve() method
Thanks for giving me something to think about
Its from my damn phone!!!
i made some edits and ran into a problem where my intent was caught be onReive() but the local variable called count never incremented... this is crazy! a block of code that would execute whenever a particular intent was recieved never did what i wanted:
count++;
refreshWidgets();
Toast.makeText(.... some indication this was done ...);
the toast was always displayed but the count never incremented. i thought the refreshWidgets method was bunk so i manually set the count in the method... everything was good... then i make a toast after the count++ to display count. count never incremented. well after messing around i found that i had count as a
private int count
i changed it to a
private static int count
and it worked! weird...
this is my final code that makes a number on a widget increment every couple of seconds. note: setting a repeating alarm with the AlarmManager for a small amount of time did not work. i had to make a nested one time alarm that kept rearming itself. and i got rid of the service cause some of the debuging tools in cm7 said it never started. cross that bridge when i get there....
Code:
package com.tsb.gmailinboxtextcloud;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
import android.widget.Toast;
public class GITextCloud extends AppWidgetProvider {
private static int count = 0;
private static int widgetCount = 0;
public static final String INCREMENT_COUNT_UPDATE = "INCREMENT_COUNT_UPDATE";
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
count = 0;
setOneTimeAlarm(this.getClass(), context);
}
@Override
public void onDisabled(Context context) {
super.onDisabled(context);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if (intent.getAction().equals("android.appwidget.action.APPWIDGET_ENABLED")) {
} else if (intent.getAction().equals("android.appwidget.action.APPWIDGET_DISABLED")) {
} else if (intent.getAction().equals(INCREMENT_COUNT_UPDATE)) {
count++;
refreshViews(context);
Toast.makeText(context, "widget #" + widgetCount, Toast.LENGTH_SHORT).show();
if (widgetCount != 0) {
setOneTimeAlarm(this.getClass(), context);
}
} else {
//Toast.makeText(context, "count = " + count + " | " + intent.getAction(), Toast.LENGTH_LONG).show();
}
}
/** Called when the activity is first created. */
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
//super.onUpdate(context, appWidgetManager, appWidgetIds);
}
private void refreshViews(Context context) {
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.main);
rv.setTextViewText(R.id.widget_textview, "" + count);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
ComponentName cName = new ComponentName(context, GITextCloud.class);
widgetCount = manager.getAppWidgetIds(cName).length;
manager.updateAppWidget(cName, rv);
}
private void setOneTimeAlarm(java.lang.Class<?> cls, Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(INCREMENT_COUNT_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (3 * 1000), pendingIntent);
}
}
hello
I am new to android application development and i am developing and application for learning purpose.
Can any body please help me in creating an activity that launch and activity on ListView Item Click.
I am using Following code for Populating Listview Items.
filename: activity_menu.java
package com.my.android.app;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.LauncherActivity.ListItem;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class activity_menu extends Activity {
String[] countries = new String[] {
"Contacts",
"SMS",
"Files & Photos",
"Prefrences",
"Logout",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
R.drawable.phonebook,
R.drawable.sms,
R.drawable.filesphotos,
R.drawable.settings,
R.drawable.key,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Manage Contacts Backup",
"Manage SMS Backup",
"Manage files & Photos Backup",
"Set your prefrences",
"Logout of Application",
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<5;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", countries);
hm.put("cur", currency);
hm.put("flag", Integer.toString(flags) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
Please help on this. waiting for Responses.
Try this
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do your action here
}
});
There are multiple ways. If using a ListFragment/ListActivity, onListItemClick can also be used. However, I think that that is used especially with a programmatically-defined ListView.
If you want to start a new Activity, do some research about Intents.
SagiLo said:
Try this
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Do your action here
}
});
Click to expand...
Click to collapse
This. Use the position parameter if you want it to only open when a particular item is clicked (It is zero-based, if I remember correctly)
Then, to open the Intent:
Code:
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
Opening on any listitem click:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
});
Opening on a specific item:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
how so i implement the code to open new activity on row cick?
cyr0s said:
This. Use the position parameter if you want it to only open when a particular item is clicked (It is zero-based, if I remember correctly)
Then, to open the Intent:
Code:
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
Opening on any listitem click:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
});
Opening on a specific item:
Code:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
Click to expand...
Click to collapse
How do i implement this code in my main activity's java file?
suppose, i have a main activity which contains the listview and i have another activity "Activity_game"
and i want to open Activity_game on clicking the first row,
so i put "0" at "ITEM_POSITION_HERE" and "game" at the place of "ActivityName"
but it gives my a bunch of errors and it doesn't work
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
nnnn1111 said:
How do i implement this code in my main activity's java file?
suppose, i have a main activity which contains the listview and i have another activity "Activity_game"
and i want to open Activity_game on clicking the first row,
so i put "0" at "ITEM_POSITION_HERE" and "game" at the place of "ActivityName"
but it gives my a bunch of errors and it doesn't work
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
if (position == ITEM_POSITION_HERE)
{
Intent myIntent = new Intent(getApplicationContext(), ActivityName.class);
startActivity(myIntent);
}
}
});
Click to expand...
Click to collapse
We need to know which errors you get.
Read this: http://forum.xda-developers.com/showthread.php?t=2439748
one question
nikwen said:
We need to know which errors you get.
Read this: http://forum.xda-developers.com/showthread.php?t=2439748
Click to expand...
Click to collapse
my problem is , when i run the app, it doesn't show any rows , not even any listview , or string
(just blank white page)
i have two activities
first one is Activity_main.xml in which ive implemented listview
here is it's java file
package com.example.desi;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
public class MainActivity extends Activity {
String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5" };
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(this, Munda.class);
startActivity(newActivity);
break;
}
}
}
and another activity is Activity_munda.xml
so, i want to run "Activity_munda" through on row click of listview
i also want to have many activities later in my app
my project is error free right now
do you think i have incomplete code?
nnnn1111 said:
my problem is , when i run the app, it doesn't show any rows , not even any listview , or string
(just blank white page)
i have two activities
first one is Activity_main.xml in which ive implemented listview
here is it's java file
package com.example.desi;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
public class MainActivity extends Activity {
String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5" };
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position )
{
case 0: Intent newActivity = new Intent(this, Munda.class);
startActivity(newActivity);
break;
}
}
}
and another activity is Activity_munda.xml
so, i want to run "Activity_munda" through on row click of listview
i also want to have many activities later in my app
my project is error free right now
do you think i have incomplete code?
Click to expand...
Click to collapse
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
vijai2011 said:
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
Click to expand...
Click to collapse
Right. Read this: http://www.vogella.com/articles/AndroidListView/article.html
i already tried that
vijai2011 said:
Your code is incomplete. You haven't populated the layout "activity_main.xml" here. and haven't added the list view, So it is indeed correct the app displays a blank page with no errors.
Click to expand...
Click to collapse
but with no luck
its very complicated
can you please give me a simple tutorial ?
please dont refer to any other tutorial as i have already tried all of them,
thanks
nnnn1111 said:
but with no luck
its very complicated
can you please give me a simple tutorial ?
please dont refer to any other tutorial as i have already tried all of them,
thanks
Click to expand...
Click to collapse
Come on, you haven't tried all of them. Please don't let everyone else do the work for you. And if you can manage to do it yourself, it will be a better learning experience.
I can offer that you try the tutorial I posted and if your code doesn't work, you can post it together with a logcat and we'll check it.
haha i know
nikwen said:
Come on, you haven't tried all of them. Please don't let everyone else do the work for you. And if you can manage to do it yourself, it will be a better learning experience.
I can offer that you try the tutorial I posted and if your code doesn't work, you can post it together with a logcat and we'll check it.
Click to expand...
Click to collapse
but ive been searching for like 15 days about this problem on stack overflow , saw like 30 posts but they arent clear , please do me a favor and
tell me in few steps you will also feel good helping me.
and it will be a VERY big favor to me , trust me
nnnn1111 said:
but ive been searching for like 15 days about this problem on stack overflow , saw like 30 posts but they arent clear , please do me a favor and
tell me in few steps you will also feel good helping me.
and it will be a VERY big favor to me , trust me
Click to expand...
Click to collapse
Read this about ListActivity. It should answer your questions: http://www.vogella.com/articles/AndroidListView/article.html#listactivity
And I won't post step by step guides on how to implement ListViews. There are many great tutorials out there. I can help you if you have problems/errors with your code, but @vijai2011 has already explained what you need to do.
You cannot expect anyone to spoon feed you. We are here to help people who try to do something but run into problems. Not people who doesnt even try to understand what they do. The guides by vogella are very simple and there is no problem with the guide. You cannot simply copy paste the codes from the tutorial and expect it to compile and work.
vijai2011 said:
You cannot expect anyone to spoon feed you. We are here to help people who try to do something but run into problems. Not people who doesnt even try to understand what they do. The guides by vogella are very simple and there is no problem with the guide. You cannot simply copy paste the codes from the tutorial and expect it to compile and work.
Click to expand...
Click to collapse
i didn't find my answer on that website
nnnn1111 said:
i didn't find my answer on that website
Click to expand...
Click to collapse
Then it may mean that you dont know what you are searching for! Because the tutorial is all about what you need - ListView!
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Makbrar3215 said:
I am pretty new to coding and app development. After searching around this is an easy thing to do. But I'm so stupid I can figure it out.
So what I need is to add a hardware function to a toggle switch. If you know how to add function to it. What I need is to send all audio through the earpiece when the toggle switch is on. Can you please put the whole code I need to do this? Please help me out!
Click to expand...
Click to collapse
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Problem!
vijai2011 said:
After you define your toggle switch in your xml, you can add a id and then you can
Code:
android:onClick="onSwitchClicked"
anywhere between the toggle block. This will say what to do when the toggle is clicked. Now put the below method in your class to control the toggle status:
Code:
public void onSwitchClicked(View view) {
switch(view.getId()){
case R.id.switch1:
if(switch1.isChecked()) {
// To do when 1st switch is on
}
else {
//To do when 1st switch is off
}
break;
case R.id.switch2:
if(switch2.isChecked()) {
//To do when 2nd switch is on
}
else {
//To do when 2nd switch is off
}
break;
}
}
You can extended to as many switches you want by providing different id's for the switch in xml and controlling that with case statements in the java.
And for controlling the audio, You can use audiomanager class
Code:
AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.setSpeakerphoneOn(true); //sets audio via speaker
am.setWiredHeadsetOn(true); //sets audio via headset
Click to expand...
Click to collapse
I did what you said. Yet I encountered a problem. Please see the attached screenshot.
When I hover over the X it says "Attribute name "public" associated with an element type "RadioButton" must be followed by the ' = '
character."
Where do I put the "="
Thanks by the way. You helped me out a lot!
you are mixing java with XML. Honestly, I suggest you start on a few beginner tutorials.
Just tell me what to do. I can't go through the guide. I need this app done by August 14.
Sent from my SGH-I337M using xda app-developers app
Bad Attitude to have. This isn't a "do my work for me" forum.
And like zalez was kind enough to point out, your putting java in xml. If you expect to make an app you need to read some beginner guides first.
you have almost a month to do it.
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Makbrar3215 said:
Thanks, I didn't mean to be rude. Where can I find the guide? :thumbup:
Sent from my SGH-I337M using xda app-developers app
Click to expand...
Click to collapse
http://developer.android.com/training/index.html
But you should probably start with generic Java 101 stuff
Set Switch status from incoming JSON data
Sorry to bump this thread after such a long time but I am facing a problem with switches myself and would appreciate some help. I have a JSON parser class which is retrieving data from a database. The retrieved info contains 'ID', 'name' and 'status' fields related to a device. I can display ID and name of each of the devices (there are several rows) using a listview but I don't know how to use the 'status' field value (it is either 1 or 0) to set an associated Switch component. I have to set the Switch associated with each listview item to ON if incoming 'status' value is 1 and set it OFF if 'status' is 0. I am lost on where to put the 'setChecked' method for every listview item. Here's the code of activity that shows these list items:
Code:
package com.iotautomationtech.androidapp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ToggleButton;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Switch;
import android.widget.TextView;
public class AllDevicesActivity extends ListActivity {
Switch mySwitch = (Switch) findViewById(R.id.switchButton);
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products = "external_link_removed";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "devices";
private static final String TAG_PID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray products = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_devices);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditDeviceActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllDevicesActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String status = c.getString(TAG_STATUS);
int toggleValue = Integer.parseInt(c.getString(TAG_STATUS));
boolean sBool = false;
if (toggleValue == 1) {
sBool = true;
}
if (status.equals("1")) {
status = "Status: ON";
}
else {
status = "Status: OFF";
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_STATUS, status);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewDeviceActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllDevicesActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME, TAG_STATUS},
new int[] { R.id.pid, R.id.name, R.id.status });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
The XML file:
Code:
<RelativeLayout xmlns:android="schemas.android"
android:layout_width="fill_parent"
android:layout_height="65dip"
android:orientation="vertical"
android:layout_centerVertical="true"
>
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="@+id/pid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="6dip"
android:textSize="17dip"
android:layout_below="@+id/name"
/>
<Switch
android:id="@+id/switchButton"
android:layout_alignParentRight="true"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:layout_marginRight="6dip"
android:layout_centerVertical="true"
android:textOff="OFF"
android:textOn="ON"
android:onClick="onSwitchClicked"
/>
</RelativeLayout>
I have reached thus far with the code: [attached-image]
Now I only have to set those Switches according to status values from database. I have tried putting the setChecked in doInBackground method and onPostExecute method but it doesn't work. Do I have to save all status values in an array and start a loop to set all Switches? Where would that code go?
ANY kind of help/guidance here is appreciated!
good day,
i'm trying to create an app that will create options in a listview on an an activity based on the option a user selects in the previous activity
below is the code i came up with but it doesn't work.
please what am i doing wrong?
thanks in advance
package com.inveniotech.moneyventure;
/**
* Created by BolorunduroWB on 9/3/13.
*/
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
import java.util.*;
import android.content.Intent;
public class menu_options extends Activity {
SimpleAdapter simpleAdpt;
Intent intent = getIntent();
public String message = intent.getStringExtra(football.EXTRA_MESSAGE);
String[] menuList;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuoptionsview);
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, optionList, android.R.layout.simple_list_item_1, new String[] {"options"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position, long id) {
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
Toast.makeText(menu_options.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
}
});
}
@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;
}
// The data to show
List<Map<String, String>> optionList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
if (message.equals("5")){
menuList = new String[]{"News", "Fixtures","Results","Standings"," "};
}
else if (message.equals("6")){
menuList = new String[]{"News", "Tables"," "," "," "};
}
else if (message.equals("7")){
menuList = new String[]{"Done Deals", "Rumours","Latest News","Live","Transfer Centre"};
}
else {
menuList = new String[] {"News","Teams","Fixtures","Results","Table"};
}
optionList.add(createOptions("options", menuList[0]));
optionList.add(createOptions("options", menuList[1]));
optionList.add(createOptions("options", menuList[2]));
optionList.add(createOptions("options", menuList[3]));
optionList.add(createOptions("options", menuList[4]));
}
private HashMap<String, String> createOptions(String key, String name) {
HashMap<String, String> options = new HashMap<String, String>();
options.put(key, name);
return options;
}
}
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
SimplicityApks said:
Read This guide first, then it's easier to help you.
What I'm seeing is that you should set your message=getIntent ().... ; in the onCreate since the Intent data is probably not available before.
Click to expand...
Click to collapse
Thank you. Wanted to post the link, too. :laugh:
I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
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;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// 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_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.