Hi guys! Well, i am facing an issue when trying to develop my app. Let me explain what i have done:
1) Create a Login to connect to a MySQL Database to validate the user (Works great)
2) Create a Main activity
3) Create a Drawer, with a Drawer Adapter, to show the options of my dramer menu. (works great)
As you know the drawer works with fragments, so i have one fragment for each menu option.
4) Well, here starts my problem...
The first option on my menu is "Fixture" where i want to show a list of matchs with the differents results. That list, is on a MySql DB.
So, on my fragment (FixtureFragment) i have this code:
Code:
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.lxp.app.adapter.FixtureAdapter;
import com.lxp.app.model.FixtureItem;
import com.lxp.app.tools.JSONParser;
import com.lxp.app.R;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class FixtureFragment extends Fragment {
// Progress Dialog
private ProgressDialog pDialog;
// url to get all products list
private static String url_fixture = "http://www.myweb.com/myFixtureData.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_FIXUTRE = "fixture";
private static final String TAG_EQUIPO1 = "id_equipo_1";
private static final String TAG_EQUIPO2 = "id_equipo_2";
private static final String TAG_GEQUIPO1 = "goles_equipo_1";
private static final String TAG_GEQUIPO2 = "goles_equipo_2";
private static final String TAG_ID_PARTIDO = "id_partido";
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
// products JSONArray
JSONArray partidos = null;
ArrayList<HashMap<Integer, FixtureItem>> fixtureList;
ListView lv;
public FixtureFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
/**
* Background Async Task to Load the fixture by making HTTP Request
* */
class LoadFixture extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando el Fixture...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting the Fixture 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_fixture, "GET", params);
// Check your log cat for JSON reponse
Log.d("Fixture: ", json.toString());
FixtureItem objFixture = new FixtureItem();
try {
// Checking for SUCCESS TAG
int success = 0;
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
partidos = json.getJSONArray(TAG_FIXUTRE);
// looping through All Products
for (int i = 0; i < partidos.length(); i++) {
JSONObject c = partidos.getJSONObject(i);
Log.e("Json = ", c.toString());
// Storing each json item in variable
String equipo1 = c.getString(TAG_EQUIPO1);
String equipo2 = c.getString(TAG_EQUIPO2);
String golesEq1 = c.getString(TAG_GEQUIPO1);
String golesEq2 = c.getString(TAG_GEQUIPO2);
Integer idPartido = c.getInt(TAG_ID_PARTIDO);
// creating new HashMap
HashMap<Integer, FixtureItem> map = new HashMap<Integer, FixtureItem>();
// adding each child node to HashMap key => value
objFixture.setGolesEquipo1(golesEq1);
objFixture.setGolesEquipo2(golesEq2);
objFixture.setIdequipo1(equipo1);
objFixture.setIdequipo2(equipo2);
objFixture.setIdPartido(idPartido);
map.put(idPartido, objFixture);
fixtureList.add(map);
}
}
} 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
lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
}
}
}
Well, as you could see, i've created a hashmap to load my fixture data, and then i sent this data (fixtureList) to the custom adapter.
When running this code i am getting this error.
Code:
04-05 16:20:27.899 23500-23500/com.lxp.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.lxp.app, PID: 23500
java.lang.NullPointerException
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:175)
at com.lxp.app.drawer.FixtureFragment$LoadFixture.onPostExecute(FixtureFragment.java:81)
at android.os.AsyncTask.finish(AsyncTask.java:632)
Line 175 --> lv.setAdapter(new FixtureAdapter(getActivity(), fixtureList));
These are the layouts files:
Fragment_Fixture.xml
Code:
<LinearLayout 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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="@+id/fixture_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
fixture_item.xml
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/idpartido"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:visibility="gone"/>
<TextView
android:id="@+id/golesequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="0"/>
<TextView
android:id="@+id/golesequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="1"/>
</LinearLayout>
<LinearLayout android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/idequipo1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Argentinos"/>
<TextView
android:id="@+id/idequipo2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="6dip"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:paddingBottom="6dip"
android:textSize="17dip"
android:textStyle="bold"
android:text="Lanus"/>
</LinearLayout>
</LinearLayout>
My fixtureitem class
Code:
public class FixtureItem {
private Integer idPartido;
private String idequipo1;
private String idequipo2;
private String golesEquipo1;
private String golesEquipo2;
public Integer getIdPartido() {
return idPartido;
}
public void setIdPartido(Integer idPartido) {
this.idPartido = idPartido;
}
public String getIdequipo1() {
return idequipo1;
}
public String getIdequipo2() {
return idequipo2;
}
public String getGolesEquipo1() {
return golesEquipo1;
}
public String getGolesEquipo2() {
return golesEquipo2;
}
public void setIdequipo1(String idequipo1) {
this.idequipo1 = idequipo1;
}
public void setIdequipo2(String idequipo2) {
this.idequipo2 = idequipo2;
}
public void setGolesEquipo1(String golesEquipo1) {
this.golesEquipo1 = golesEquipo1;
}
public void setGolesEquipo2(String golesEquipo2) {
this.golesEquipo2 = golesEquipo2;
}
}
and my fixture adapter
Code:
public class FixtureAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
public FixtureAdapter(Context context, ArrayList listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.fixture_item, null);
holder = new ViewHolder();
holder.idequipo1 = (TextView) convertView.findViewById(R.id.idequipo1);
holder.idequipo2 = (TextView) convertView.findViewById(R.id.idequipo2);
holder.golesequipo1 = (TextView) convertView.findViewById(R.id.golesequipo1);
holder.golesequipo2 = (TextView) convertView.findViewById(R.id.golesequipo2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
FixtureItem fixtureItem = (FixtureItem) listData.get(position);
holder.idequipo1.setText(fixtureItem.getGolesEquipo1());
holder.idequipo2.setText(fixtureItem.getGolesEquipo2());
holder.golesequipo1.setText(fixtureItem.getGolesEquipo1());
holder.golesequipo2.setText(fixtureItem.getGolesEquipo1());
return convertView;
}
static class ViewHolder {
TextView idequipo1;
TextView idequipo2;
TextView golesequipo1;
TextView golesequipo2;
}
}
I think i am getting wrong because i couldnt find an example of loading data in an asyncronous way for a list inside a fragment, i know is too expecific this example, but i tried differents ways to do it and i couldnt solve it.
If an experienced dev could give me a hand, i will be glad. Or if you have examples of an app working with "Drawer/Fragment/Custom List inside Fragments/Data Loaded from a MySql for the Custom List" it will be great.
If you need more data, just let me know.
Hey i made two apps with remote mysql database . May be i can help .
Sent from my SM-G900T using Tapatalk
Change
Try changing this:
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
// Loading products in Background Thread
new LoadFixture().execute();
return fixtureView;
}
from
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Hashmap for ListView}
fixtureList = new ArrayList<HashMap<Integer, FixtureItem>>();
// Loading products in Background Thread
new LoadFixture().execute();
View fixtureView = inflater.inflate(R.layout.fragment_fixture, container, false);
return fixtureView;
}
Same problem
I have the same problem, not able to solve?
Resolved!!
Missed make reference to listView after inflate places:
lv = (ListView) view.findViewById(R.id.fixture_list);
Click to expand...
Click to collapse
Hugs,
Léo
can anybody help me im trying to display the results in the fragment from customlistview adapter ,there is no error at all but its not also displaying the results..
Related
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!
Dears,
I have an expandable list view in Android application, I want to achieve the following:
When long click on group item, all its children should be selected.
vehicle_group_item.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""""
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/vehicle_group_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="25dp"/>
</LinearLayout>
vehicle_item.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""""
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp" >
<TextView
android:id="@+id/vehicle_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:paddingLeft="25dp" />
<ImageView
android:id="@+id/is_selected"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/>
</RelativeLayout>
VehicleListAdapter.java:
Code:
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class VehicleListAdapter extends BaseExpandableListAdapter {
private Activity context;
private Map<String, List<String>> vehicleGroupCollection;
private List<String> vehicleGroupsList;
public VehicleListAdapter(Activity context, List<String> vehicleGroupsList,
Map<String, List<String>> vehicleGroupCollection) {
this.context = context;
this.vehicleGroupsList = vehicleGroupsList;
this.vehicleGroupCollection = vehicleGroupCollection;
}
public Object getChild(int groupPosition, int childPosition) {
return vehicleGroupCollection.get(vehicleGroupsList.get(groupPosition)).get(childPosition);
}
public Object getChildren(int groupPosition) {
return vehicleGroupCollection.get(vehicleGroupsList.get(groupPosition));
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String vehicle = (String) getChild(groupPosition, childPosition);
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.vehicle_item, null);
}
TextView item = (TextView) convertView.findViewById(R.id.vehicle_name);
ImageView isSelected = (ImageView) convertView.findViewById(R.id.is_selected);
item.setText(vehicle);
return convertView;
}
public int getChildrenCount(int groupPosition) {
return vehicleGroupCollection.get(vehicleGroupsList.get(groupPosition)).size();
}
public Object getGroup(int groupPosition) {
return vehicleGroupsList.get(groupPosition);
}
public int getGroupCount() {
return vehicleGroupsList.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String groupName = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.vehicle_group_item,
null);
}
TextView item = (TextView) convertView.findViewById(R.id.vehicle_group_name);
item.setTypeface(null, Typeface.BOLD);
item.setText(groupName);
return convertView;
}
public boolean hasStableIds() {
return true;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
In main activity OnCreate method:
Code:
createGroupList();
createCollection();
MyExpandableList = (ExpandableListView) findViewById(R.id.MyExpandableList);
final ExpandableListAdapter expListAdapter = new VehicleListAdapter(
this, vehicleGroupList, vehicleGroupCollection);
MyExpandableList.setAdapter(expListAdapter);
MyExpandableList.setLongClickable(true);
MyExpandableList.setOnItemLongClickListener(new OnItemLongClickListener() {
[user=439709]@override[/user]
public boolean onItemLongClick(AdapterView<?> parent, View v,
int groupPosition, long id) {
int itemType = ExpandableListView.getPackedPositionType(id);
if(itemType == ExpandableListView.PACKED_POSITION_TYPE_GROUP){
List<String> mySelectedCollection = (List<String>) ((VehicleListAdapter) expListAdapter).getChildren(groupPosition);
if(mySelectedCollection != null){
for (String vehiclepName : mySelectedCollection) {
Toast.makeText(getBaseContext(), vehiclepName, Toast.LENGTH_LONG).show();
}
return true;
}
else{
return false;
}
}
return true;
}
});
The output of the main activity code is Toasting all children text on screen.
But, what I want to do, is to set "is_selected" in "ImageView" with Drawable image.
After long click on the group item, ALL children of this group get selected.
Regards,
Dears,
What is wrong with this question?
Is it easy question so it does not worth to answer?
Or it is tough and no body know the answer?
I'm stick with this sine weeks
Regards,
Hi guys I have a problem with the cool lib from nhaarman
I integrated successfully his lib with an activity extends ListActivity
Code:
public class MainActivity extends ListActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getListView().setDivider(null);
MyAdapter adapter = new MyAdapter();
//setListAdapter(adapter);
ScaleInAnimationAdapter swingRightInAnimationAdapter = new ScaleInAnimationAdapter(adapter);
swingRightInAnimationAdapter.setAbsListView(getListView());
setListAdapter(swingRightInAnimationAdapter);
for(int i = 0 ; i<10; i++)
{
adapter.add("task" + String.valueOf(i));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class MyAdapter extends ArrayAdapter<String>
{
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = (TextView) convertView;
if (tv == null) {
tv = new TextView(MainActivity.this);
}
tv.setText(getItem(position));
return tv;
}
}
}
This code above is working fine. The list_rows are fading in the screen.
But now I want to integrate this lib into a fragment with a listview within:
Code:
public class FragmentTask extends Fragment{
ListView listView;
MyAdapter adapter;
View view;
public FragmentTask() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(new Exception().getStackTrace()[0].getClassName(), new Exception().getStackTrace()[0].getMethodName());
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_tasks, container, false);
Button button = (Button) view.findViewById(R.id.btn_newTask);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapter.add("task");
adapter.notifyDataSetChanged();
}
});
listView = (ListView) view.findViewById(R.id.taskListView);
listView.setDivider(null);
adapter = new MyAdapter(view.getContext());
ScaleInAnimationAdapter swingRightInAnimationAdapter = new ScaleInAnimationAdapter(adapter);
swingRightInAnimationAdapter.setAbsListView(listView);
listView.setAdapter(swingRightInAnimationAdapter);
return view;
}
private class MyAdapter extends ArrayAdapter<String>
{
Context context;
private MyAdapter(Context context) {
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_row,parent, false);
TextView title = (TextView) row.findViewById(R.id.textView);
title.setText(getItem(position));
return row;
}
}
}
Now I have the effect that the rows only fade in if i "spam" new rows so that I have to scroll down. So the list items which were hided appear now with the fade-effect. But the other list items which have room in the listview without scrolling are not fading.
Do you understand me?
Please help me
edit: here is my fragment_tasks.xml
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout .....">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="New Task"
android:id="@+id/btn_newTask"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/taskListView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="@+id/btn_newTask"
/>
</RelativeLayout>
Hi! I am beginner in Android programming. I would like to learn how to send a string between 2 devices via Bluetooth. I was trying to write a code on the base of page http://developer.android.com/guide/topics/connectivity/bluetooth.html
I got 3 errors. The first one is, that the MainActivity is underlined red in the following row:
Code:
public class MainActivity extends Activity {
It says: 'The blank final field mHandler may not have been initialized'
The other 2 errors are shown in the AcceptThread and ConnectThread classes. The following row is underlined red:
Code:
manageConnectedSocket(socket);
It says: 'The method manageConnectedSocket(BluetoothSocket) is undefined for the type AcceptThread' and 'The method manageConnectedSocket(BluetoothSocket) is undefined for the type ConnectThread'
Could you please tell me, how to fix the problems and explain me, what were the problems? Thanks in advance.
MainActivity.java:
Code:
package com.example.probax8;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private final static int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter mBluetoothAdapter = null;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private final UUID my_UUID = UUID.fromString("00001802-0000-1000-8000-00805f9b34fb");
protected static final int MESSAGE_READ = 1;
BroadcastReceiver mReceiver;
private final Handler mHandler;
private BluetoothSocket socket;
String address;
TextView tv;
int a = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//**** Is BlueTooth and enable BT
final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
//**** ON/OFF Bluetooth on click
Button btButton = (Button) findViewById(R.id.bBT);
btButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
}
else{
mBluetoothAdapter.disable();
}
}
});
//**** make Bluetooth discoverable
Button discButton = (Button) findViewById(R.id.bDis);
discButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
});
Button stopDiscButton = (Button) findViewById(R.id.bStopDisc);
stopDiscButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter.startDiscovery();
}
});
Button startDiscButton = (Button) findViewById(R.id.bStartDisc);
startDiscButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter.startDiscovery();
}
});
tv = (TextView) findViewById(R.id.textView1);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED)
{
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
tv.setText(device.getName() + "\n" + device.getAddress());
}
}
}
};
//****
mNewDevicesArrayAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
ListView newDevicesListView = (ListView) findViewById(R.id.listView1);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
mNewDevicesArrayAdapter.notifyDataSetChanged();
// newDevicesListView.setOnItemClickListener(mDeviceClickListener);
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
// If there are paired devices
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
newDevicesListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
// mBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
//get the device address when click the device item
address = info.substring(info.length()-17);
a = 1;
Log.e(TAG, address);
//connect the device when item is click
BluetoothDevice connect_device = mBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(my_UUID);
socket.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});//************new_devices_list end
if(a==1){
Toast.makeText(this, address,Toast.LENGTH_LONG).show();
}
Button unregButton = (Button) findViewById(R.id.bUnreg);
unregButton.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
unregisterReceiver(mReceiver);
}
});
//**************
class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("MainActivity", my_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(socket);
mmServerSocket.close();
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
//***********
class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(my_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
//**********
class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
}
activity_main.xml:
Code:
<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"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/bBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:text="Bluetooth" />
<Button
android:id="@+id/bDis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/bBT"
android:text="Disc 300s" />
<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/bDis" >
</ListView>
<Button
android:id="@+id/bRetry"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/bBT"
android:layout_alignBottom="@+id/bBT"
android:layout_toRightOf="@+id/bBT"
android:text="Retry" />
<Button
android:id="@+id/bUnreg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/bRetry"
android:layout_toRightOf="@+id/bRetry"
android:text="Unregister" />
<Button
android:id="@+id/bStopDisc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/bRetry"
android:layout_toRightOf="@+id/bDis"
android:text="StopDisc" />
<Button
android:id="@+id/bStartDisc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/bUnreg"
android:layout_toRightOf="@+id/bStopDisc"
android:text="StartDisc" />
</RelativeLayout>
Hi there
I am new to this forum as an User, and I am also new to Java and Android, in developing ways. Sorry if there are any language or other mistakes.
So I am trying to make an app for a 'final' school project, which has the follow use:
The user sees an picture, a 'next' (and a 'finish') button. there are 11 pictures (user only sees one)(in the code there are for testing purposes only 3) when the user clicks 'next', the pic no. 2 appears, if he clicks another time next, the pictuer no. 3 appears and so on. (If he clicks finish, he should see a messages which shows him the text: "you've made it until pic xy" but i'm not so far yet.) I tried to do it with this code, but i failed.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class VisusActivity extends Activity implements OnClickListener {
ImageView testanzeige;
Button next;
Integer[] bildanzeige = {
R.drawable.visustest,
R.drawable.v2,
R.drawable.v3
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(this);
next.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visus, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[0]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
};
public void onClick1(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[2]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
so what have I to do? no tutorial shows up exactly my problem ( I think it's such a basic thing everyone can do it^^)
thx
rodentooth
Anser
rodentooth said:
Hi there
I am new to this forum as an User, and I am also new to Java and Android, in developing ways. Sorry if there are any language or other mistakes.
So I am trying to make an app for a 'final' school project, which has the follow use:
The user sees an picture, a 'next' (and a 'finish') button. there are 11 pictures (user only sees one)(in the code there are for testing purposes only 3) when the user clicks 'next', the pic no. 2 appears, if he clicks another time next, the pictuer no. 3 appears and so on. (If he clicks finish, he should see a messages which shows him the text: "you've made it until pic xy" but i'm not so far yet.) I tried to do it with this code, but i failed.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class VisusActivity extends Activity implements OnClickListener {
ImageView testanzeige;
Button next;
Integer[] bildanzeige = {
R.drawable.visustest,
R.drawable.v2,
R.drawable.v3
};
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
next = (Button)findViewById(R.id.next);
next.setOnClickListener(this);
next.setOnClickListener(this);
}
[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.visus, menu);
return true;
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onClick(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[0]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
};
public void onClick1(View v) {
try {
//Toast.makeText(this, getResources().getDisplayMetrics().toString(), Toast.LENGTH_LONG).show();
testanzeige.setImageResource(bildanzeige[2]);
}catch(Exception e){
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
}
}
}
so what have I to do? no tutorial shows up exactly my problem ( I think it's such a basic thing everyone can do it^^)
thx
rodentooth
Click to expand...
Click to collapse
I have Make Fresh Java That will help You
Java
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* @author AndroidFire
*/
public class JumperPic extends Activity {
Button Nexty;
ImageView Imagey;
int i = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.jumper);
Nexty = (Button)findViewById(R.id.nextey);
Imagey = (ImageView)findViewById(R.id.imagey);
Nexty.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 2) {
//Your 3 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 3) {
//Your 4 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 10) {
//Image 11 Image
Nexty.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
}
}
Layout
Code:
<?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" >
<ImageView
android:id="@+id/imagey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/avatar_default_1" />
<Button
android:id="@+id/nextey"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
In Your Java You can use Button.setOnClickLiestner(new View.OnClickLiestner It will bit easier than it because When We Implement Anything in Your Class we need delcare methods @override somethings you can use int to change Image
In My Java I have int values that will change every click on Button according to values it will change imageview you have write java that is tough from Me you can use my one it will bit easier Ok
Thank you new problem
Thank you so very much AndroidFire withoup you i've wouldn't made it this far. So you say I can use your code (with your name in it) in my Project?
AndroidFire said:
you can use my one it will bit easier Ok
Click to expand...
Click to collapse
Now while this problem is solved another problem has come up.
As I told you in my first thread, there is a finish button. It has this use:
when user clicks next 2 times (so if he made it until the 3rd picture) and then clicks finish, he'll Return to the main activity, and instead of the text 'Klicke auf start um zu beginnen' (click on start to begin) the text 'you made it until the 3rd picture' should show up.
If he clicked Next 5 times (6th picture) and clicks finish, he also returns to the main activity, but the text is 'you made it until the 5th picture'.
And so on with the others.
now i dont know, how to implement multiple buttons, how can I learn that? also how did you learn to code, AndroidFire? It's such a masterpiece *-*
I've tried this, but I failed.
the red lines are those, which I made at my own but they unfortunately don't work
Java Main Activity
Code:
package ch.OptiLab.visustest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.buttonSTART);
btn1.setOnClickListener(this);
[COLOR="red"] Intent intent = getIntent();
if( intent != null)
String inhalt = intent.GetStringExtra("0.1");[/COLOR]
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(this,VisusActivity.class));
}
}
XML Main Activity
Code:
<RelativeLayout xmlns:android="(external link)"
xmlns:tools="(external link)"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="ch.OptiLab.visustest.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@string/Text1"
android:id="@+id/textView"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:gravity="center_horizontal"
android:singleLine="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="@string/Text2"
android:id="@+id/textView2"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
<Button
android:id="@+id/buttonSTART"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="@string/button1"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="142dp" />
</RelativeLayout>
Java 2nd activity
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* @author AndroidFire
*/
public class VisusActivity extends Activity {
Button next;
ImageView testanzeige;
Button finish;
int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
next = (Button)findViewById(R.id.next);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
[COLOR="red"]finish = (Button)findViewById(R.id.finish);[/COLOR]
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
testanzeige.setImageResource(R.drawable.visustest);
[COLOR="Red"]finish.setOnClickListener(new View.OnClickListener() {
Intent i = new Intent(this, MainActivity.class);
String content = "You made it until 2nd picture".toString();
i.putExtra("0.1", content);
}
[/COLOR]
}
else if (i == 2) {
//Your 3 Image
testanzeige.setImageResource(R.drawable.v2);
}
else if (i == 3) {
//Your 4 Image
testanzeige.setImageResource(R.drawable.v3);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 10) {
//Image 11 Image
next.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
}
}
XML 2nd Activity
Code:
<RelativeLayout xmlns:android="(external link)"
(external link)"
android:layout_width="match_parent"
android:layout_height="match_parent"
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="ch.OptiLab.visustest.VisusActivity" >
<ImageView
android:id="@+id/testanzeige"
android:layout_width="231dp"
android:layout_height="231dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/v2" />
<Button
android:id="@+id/next"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"
android:text="@string/NEXTPIC" />
<Button
android:id="@+id/finish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/next"
android:layout_alignBottom="@+id/next"
android:layout_alignParentLeft="true"
android:text="@string/cantread" />
</RelativeLayout>
The most important strings:
Code:
<string name="Text1">Klicke auf Start um zu beginnen.</string>
<string name="cantread">finish</string>
Thank you so much
other way also not work
Well I have tried another solution, but it didn't work either. What do I have to do?
Code:
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
/**
* [user=736105]@author[/user] AndroidFire
*/
public class VisusActivity extends Activity {
Button next;
ImageView testanzeige;
Button finish;
int i = 0;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visus);
next = (Button)findViewById(R.id.next);
testanzeige = (ImageView)findViewById(R.id.testanzeige);
finish = (Button)findViewById(R.id.finish);
next.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
// To Set Your 1 Image Do it Thorough Layout
if (i == 1 ) {
//Your 2 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 2) {
//Your 3 Image
testanzeige.setImageResource(R.drawable.v2);
}
else if (i == 3) {
//Your 4 Image
testanzeige.setImageResource(R.drawable.v3);
}
else if (i == 4) {
// Your 5 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 5 ) {
//Your 6 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 6) {
//Your 7 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 7 ) {
//Your 8 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 8 ) {
//Your 9 Image
//Imagey.setImageResource(R.drawable.Your Image);
}
else if (i == 9) {
//Your 10 Image
testanzeige.setImageResource(R.drawable.visustest);
}
else if (i == 10) {
//Image 11 Image
next.setText("Finish");
Toast.makeText(getApplicationContext(), "Your Final Text", Toast.LENGTH_LONG).show();
}
}
});
[COLOR="Red"]finish.setOnClickListener(new View.OnClickListener() {
Intent i = new Intent(this, MainActivity.class);
[user=439709]@override[/user]
public void onClick(View arg0) {
i++;
if (i == 1 ) {
String content = "You got 0.1".toString();
i.putExtra("0.1", content);
[/COLOR]
}
}
}
}
I'm assuming you declared your activity in the Manifest?
F'n noob said:
I'm assuming you declared your activity in the Manifest?
Click to expand...
Click to collapse
uhm I think so.
Edit: there are 2 activity-groups in my manifest, so I think they've been declared automatically?
After looking at your code further, you are using onClick methods but aren't implenting an onClickListener. Are your buttons working at all?
yes, they are working fine. I just dont know how to change the text.
rodentooth said:
yes, they are working fine. I just dont know how to change the text.
Click to expand...
Click to collapse
There are two ways I can think of to solve this one.
The first is to create an Application class, declare that in the manifest, and add a variable in there to save how many images have been seen. Just set it in the one activity and in the other read it, and if it's 0, show the start message, and if it's greater than 0 show the message you want.
The cooler way is to use startActivityForResult to go to the picture viewing activity. The picture viewing activity keeps track of how many the user saw and then, when they leave:
Code:
Intent returnData = new Intent();
returnData.putExtra("PICTURES_SEEN", count);
setResult(RESULT_OK, returnData);
Then, in the first activity:
Code:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
int picturesSeen = data.getExtra("PICTURES_SEEN");
// do stuff
}
}
Hopefully that's helpful.
(There's a page in Google's API called "Getting a Result from an Activity" but I can't link to it because I'm a spammernew.)