GridView and ListView in a single fragment - android

I am doing Android Application for shopping. I need to display products as grid as well as list like this:
https://lh6.ggpht.com/Ly21pAbBRIxAzHn2R119a37NexxtjG5RkQJV8vv0IoCywzksIhKNSCkzWikbUnH8bGY=h900-rw
I don't know how to do this using image button or tabs. Can I change layout of the fragment at runtime? Or I have use 2 different fragments? Please help me.

You have multiple options:
Use RecyclerView
Have two different fragments
Have two different layouts
Use a Framelayout and switch visibility of sub views
Use a ViewFlipper or ViewSwitcher

Why use two layouts when you can simply use RecyclerView and use an imagebutton to handle the clicks and when clicked you can use something like this
// The number of Columns
mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
and when the listbutton is clicked you can use something like this:
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
I'm not sure whether it would work or not, its just an example,If you want to learn more about implementing girds and lists using RecyclerView and CardView, check out these tutorials I made:
Custom Android lists with CardView and RecyclerView
Custom Android Grids with Images and Texts using RecyclerView

Just look at this:
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<LinearLayout
android:id="#+id/tlist"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" >
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ListView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
<LinearLayout
android:id="#+id/tgrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center" >
<TextView
android:id="#+id/textview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GridView"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/white" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.1" >
<LinearLayout
android:id="#+id/gridid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:visibility="gone" >
<GridView
android:id="#+id/gridView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:horizontalSpacing="5dp"
android:numColumns="2"
android:verticalSpacing="5dp" >
</GridView>
</LinearLayout>
<LinearLayout
android:id="#+id/listid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dividerHeight="10sp" >
</ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>
MainActivity.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.Adapter.FriendAdapter;
import com.example.bean.FriendBean;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
private ListView mlist;
private GridView mgrid;
private ArrayList<FriendBean> arr = new ArrayList<FriendBean>();
private FriendAdapter friendAdapter1, friendAdapter2;
private int slist = R.layout.list;
private int sgrid = R.layout.grid;
private TextView list, grid;
LinearLayout listid, gridid, tlist, tgrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mlist = (ListView) findViewById(R.id.listView1);
mgrid = (GridView) findViewById(R.id.gridView1);
list = (TextView) findViewById(R.id.textview1);
grid = (TextView) findViewById(R.id.textview2);
listid = (LinearLayout) findViewById(R.id.listid);
gridid = (LinearLayout) findViewById(R.id.gridid);
tlist = (LinearLayout) findViewById(R.id.tlist);
tgrid = (LinearLayout) findViewById(R.id.tgrid);
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(
"listgrid.json")));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
br.close(); // stop reading
} catch (IOException e) {
e.printStackTrace();
}
}
String myjsonstring = sb.toString();
try {
JSONObject obj = new JSONObject(myjsonstring);
JSONArray jsonarray = obj.getJSONArray("lg");
Log.e("Length", "" + jsonarray.length());
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonObj = jsonarray.getJSONObject(i);
String num = jsonObj.getString("number");
String url = jsonObj.getString("image_url");
FriendBean bean = new FriendBean(url, num);
arr.add(bean);
Log.e("image_url", url);
Log.e("number", num);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tlist.setBackgroundColor(Color.RED);
tgrid.setBackgroundColor(Color.BLACK);
friendAdapter1 = new FriendAdapter(MainActivity.this, slist, arr);
mlist.setAdapter(friendAdapter1);
/*****JUST LOOK AT THIS****/
list.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gridid.setVisibility(View.GONE);
listid.setVisibility(View.VISIBLE);
tlist.setBackgroundColor(Color.RED);
tgrid.setBackgroundColor(Color.BLACK);
friendAdapter1 = new FriendAdapter(MainActivity.this, slist, arr);
mlist.setAdapter(friendAdapter1);
}
});
/*****JUST LOOK AT THIS****/
grid.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
gridid.setVisibility(View.VISIBLE);
listid.setVisibility(View.GONE);
tgrid.setBackgroundColor(Color.RED);
tlist.setBackgroundColor(Color.BLACK);
friendAdapter2 = new FriendAdapter(MainActivity.this, sgrid, arr);
mgrid.setAdapter(friendAdapter2);
}
});
}
}

Related

Android ListView not wrapping text

I made a client program on my android and when I receive long messages it doesn't show the whole msg. I have tried to add android:orientation="horizontal" to the XML file but that didn't fix anything.
package com.example.marcus.chatclient1;
import android.app.Activity;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Array;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import static android.R.layout.list_content;
public class chat extends Activity {
Handler hanGET;
String string = "test";
String name;
EditText msgBox;
Button sButton;
ListView lv;
TextView errorT;
ObjectOutputStream o;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Button join = (Button) findViewById(R.id.joinButton);
final EditText nameT = (EditText) findViewById(R.id.editTextName);
msgBox = (EditText)findViewById(R.id.msgField);
sButton = (Button)findViewById(R.id.sendButton);
errorT = (TextView) findViewById(R.id.errorText);
lv = (ListView)findViewById(R.id.ChatList);
msgBox.setVisibility(View.INVISIBLE);
sButton.setVisibility(View.INVISIBLE);
lv.setVisibility(View.INVISIBLE);
join.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name = nameT.getText().toString();
join.setVisibility(View.INVISIBLE);
nameT.setVisibility(View.INVISIBLE);
lv.setVisibility(View.VISIBLE);
msgBox.setVisibility(View.VISIBLE);
sButton.setVisibility(View.VISIBLE);
new Thread(new ClientThread()).start();
final ArrayList<String> ar = new ArrayList<String>();
final ArrayAdapter ad = new ArrayAdapter(getApplicationContext(),android.R.layout.simple_gallery_item, ar);
lv.setBackgroundColor(Color.BLACK);
lv.setAdapter(ad);
hanGET = new Handler(){
public void handleMessage(Message message) {
ar.add(string);
ad.notifyDataSetChanged();
}
};
}
});
}
class ClientThread implements Runnable {
public void run() {
Message message;
Socket s;
try {
s = new Socket("192.168.0.15", 55555);
o = new ObjectOutputStream(s.getOutputStream());
o.writeObject(name);
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
sButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
String m = msgBox.getText().toString();
o.writeObject(m);
} catch (IOException e) {
e.printStackTrace();
}
}
});
while(true) {
try {
string = in.readObject().toString();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
message = Message.obtain();
hanGET.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
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="com.example.marcus.chatclient1.chat">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Join"
android:id="#+id/joinButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text="Name"
android:ems="10"
android:id="#+id/editTextName"
android:layout_marginBottom="31dp"
android:layout_above="#+id/joinButton"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/errorText"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ChatList"
android:layout_alignParentTop="true"
android:clickable="false"
android:layout_alignBottom="#+id/joinButton"
android:choiceMode="none"
tools:listitem="#android:layout/simple_gallery_item"
tools:listfooter="#layout/activity_chat"
android:visibility="visible"
android:layout_centerHorizontal="true"
android:headerDividersEnabled="false" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/msgField"
android:layout_below="#+id/ChatList"
android:layout_toRightOf="#+id/errorText"
android:layout_toEndOf="#+id/errorText"
android:visibility="visible" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send"
android:id="#+id/sendButton"
android:layout_alignBottom="#+id/msgField"
android:layout_toRightOf="#+id/joinButton"
android:layout_toEndOf="#+id/joinButton"
android:visibility="visible" />
</RelativeLayout>
A ListView must have the layout_height attribute not setted to wrap_content. A ListView content height is dynamic, since you don't always have the same number of cells. Thus, you need to match the parent size or have a fixed height.

show EditText on condition

Right now I have an idea for a project and I would like to know if anyone can help me on the same logic.
As such I need to create or generate a number of EditText according to amount you enter, ie, to select or enter a number such as 5, show me 5 EditText layout for type 5 values​​. They know that the form could accomplish this? Any ideas please?
I guess it must be a way to do it with a loop, but not like carrying this calculation Java to XML. Thank you.
Here is an example of generating EditText items based on the number you enter. You can ignore the scrollview in the layout file I just put it in case someone added a lot of EditText items that would go off the screen.
MainActivity.java
package com.example.test;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText count = (EditText) findViewById(R.id.count);
final TextView output = (TextView) findViewById(R.id.output);
final Button generate = (Button) findViewById(R.id.generate);
final Button values = (Button) findViewById(R.id.values);
final LinearLayout container = (LinearLayout) findViewById(R.id.container);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int numberOfControlsToGenerate = 0;
try {
numberOfControlsToGenerate = Integer.parseInt(count.getText().toString().trim());
} catch (NumberFormatException e) {
Log.e(TAG, e.getMessage(), e);
}
if (numberOfControlsToGenerate > 0) {
if (container.getChildCount() > 0) {
container.removeAllViews();
}
for (int counter = 0; counter < numberOfControlsToGenerate; counter++) {
addEditText(container);
}
}
}
});
values.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] editTextValues = new String[container.getChildCount()];
StringBuilder editTextValuesBuilder = new StringBuilder();
for (int counter = 0; counter < container.getChildCount(); counter++) {
EditText child = (EditText) container.getChildAt(counter);
editTextValues[counter] = child.getText().toString().trim();
editTextValuesBuilder.append(editTextValues[counter]).append("\n");
}
output.setText(editTextValuesBuilder.toString());
}
});
}
private void addEditText(LinearLayout container) {
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
EditText editTextToAdd = new EditText(this);
editTextToAdd.setLayoutParams(params);
container.addView(editTextToAdd);
}
}
activity_main.xml
<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:gravity="center_horizontal"
android:orientation="vertical"
android:padding="16dp"
tools:context="${packageName}.${activityClass}" >
<EditText
android:id="#+id/count"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="number"
android:textSize="20sp" />
<Button
android:id="#+id/generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
<Button
android:id="#+id/values"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Values" />
<TextView
android:id="#+id/output"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>

ftp_host cannot be resolved or not a field

I am learning android application development online I have created a project using guideline from http://www.edumobile.org/android/android-beginner-tutorials/ftp-message-viewer-in-android/ but getting error call "ftp_host cannot be resolved or not a field" and "ftp_message_result cannot be resolved or not a field".
My Layout file includes following
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView android:text="#string/ftp_server_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText android:id="#+id/ftp_host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textUri">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
<Button android:text="#string/ftp_button_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="showMessage"/>
<ScrollView android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/ftp_message_result"
android:textSize="#dimen/ftp_message_size"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</ScrollView>
</LinearLayout>
and my MainActivity file looks like below
import java.io.BufferedReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText mFtpHost;
private TextView mFtpMessageResult;
private static final int FTP_PORT = 8080;
/** Initializes the app when it is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mFtpHost = (EditText)findViewById(R.id.ftp_host);
mFtpMessageResult = (TextView)findViewById(R.id.ftp_message_result);
}
public void showMessage(View clickedButton) {
String host = mFtpHost.getText().toString();
try {
Socket socket = new Socket();//(host, FTP_PORT);
BufferedReader in = SocketUtils.getReader(socket);
List<String> results = new ArrayList<String>();
String line = in.readLine();
results.add(line);
if (line.startsWith("220-")) {
while((line = in.readLine()) != null) {
results.add(line);
if ((line.equals("220") || line.startsWith("220 "))) {
break;
}
}
}
String output = makeOutputString(results);
mFtpMessageResult.setText(output);
socket.close();
} catch (Exception e) {
mFtpMessageResult.setText("Unknown host: " + host);
e.printStackTrace(); // View this in DDMS window
}
}
private String makeOutputString(List<String> results) {
StringBuilder output = new StringBuilder();
for (String s: results) {
output.append(s + "\n");
}
return(output.toString());
}
}
Proof if your layout file is really called activity_list_item. If it isn't you have to change
setContentView(R.layout.activity_list_item);
,in your onCreate()-Method, to:
setContentView(R.layout.'THE NAME OF THE LAYOUT');

Passing variable with intents in a tab/multiple activities android app

Hi Im a beginner to android development and Im doing an school assigment where we are to make n app which has a textfield for searching which will use that string to query a open API of rotten tomatoes. This will be shown as a list and later manipulated.
I have now come til the end. Searching for, adding to and getting similar movies all work fine (and the gui too) but im not able to delete from the db/list (which i save the movies to, if wanted) and I dont know why. I think I use the intents the right way but apparently not.
FULLCODE:
// MainActivity.java
package geemoney.movieeservice;
import android.os.Bundle;
import android.app.TabActivity;
import android.content.Intent;
import android.view.Menu;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** TabHost (main container of tab view, the top rectangle) will have Tabs */
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
/** TabSpec used to create a new tab.
* By using TabSpec only we can able to setContent to the tab.
* By using TabSpec setIndicator() we can set name to tab. */
/** tid1 is firstTabSpec Id. Its used to access outside. */
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
TabSpec secondTabSpec = tabHost.newTabSpec("tid2");
/** TabSpec setIndicator() is used to set name for the tab. */
/** TabSpec setContent() is used to set content for a particular tab. */
firstTabSpec.setIndicator("Search").setContent(new Intent(this,SearchTab.class));
secondTabSpec.setIndicator("My List").setContent(new Intent(this,MylistTab.class));
/** Add tabSpec to the TabHost to display. Adding the newly created tabs to its container */
tabHost.addTab(firstTabSpec);
tabHost.addTab(secondTabSpec);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
// One of the two new classes/tabs, this one callse SearchTab
package geemoney.movieeservice;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import database.DBAdapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class SearchTab extends Activity {
ArrayList<String> list = new ArrayList<String>();
List<Map<String, String>> data;
SimpleAdapter aa;
Map<String, String> item;
String apiKey = "chhgsd429xb9fs6wq3kqzhmk";
String current = "";
MylistTab mt = new MylistTab();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
/* First Tab Content */
Button addButton = (Button) findViewById(R.id.add);
Button similarButton = (Button) findViewById(R.id.similar);
Button searchButton = (Button) findViewById(R.id.search);
addButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (current != ""){
add();
}else {
Toast.makeText(getApplicationContext(), "You need to select a list item",Toast.LENGTH_LONG).show();
}
}
});
similarButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (current != ""){
similar();
}else {
Toast.makeText(getApplicationContext(), "You need to select a list item",Toast.LENGTH_LONG).show();
}
}
});
searchButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText userInput = (EditText) findViewById(R.id.searchstring);
if ((!(userInput.getText().toString().isEmpty()))) {
search();
}else {
Toast.makeText(getApplicationContext(), "You need insert a search string",Toast.LENGTH_LONG).show();
}
}
});
}
protected void add() {
DBAdapter db = new DBAdapter(this);
String id = current.substring(current.indexOf("id=") + 3, current.indexOf(" ", current.indexOf("id=") + 3) - 1);
String title = current.substring(current.indexOf("title=") + 6, current.indexOf("}", current.indexOf("title=")));
String year = current.substring(current.indexOf("year=") + 5, current.indexOf(" ", current.indexOf("year=") + 5) - 1);
db.open();
db.insertTitle(id, title, year);
db.close();
Toast.makeText(getApplicationContext(), "Added to DB", Toast.LENGTH_LONG).show();
}
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
// HERE INTENT
Intent i = new Intent(SearchTab.this, MylistTab.class);
}});
}
private String searchquery(String searchString) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="+apiKey + "&q="+searchString + "&page_limit=10");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("QueryDB", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
//id=12897, year=1999, title=The Matrix
String id = current.substring(current.indexOf("id=") + 3, current.indexOf(" ", current.indexOf("id=") + 3) - 1);
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
// HERE INTENT
}});
}
private String similarquery(String id) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://api.rottentomatoes.com/api/public/v1.0/movies/"+id+"/similar.json?apikey="+apiKey +"&limit=5");
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("QueryDB", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
// mylisttab.java
package geemoney.movieeservice;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import database.DBAdapter;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
public class MylistTab extends Activity {
ArrayList<String> list = new ArrayList<String>();
List<Map<String, String>> data;
SimpleAdapter aa;
DBAdapter db = new DBAdapter(this);
String current = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylist);
/* First Tab Content */
Button deleteButton = (Button) findViewById(R.id.remove);
deleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (current != "") {
delete();
}else {
Toast.makeText(getApplicationContext(), "You need to select a list item",Toast.LENGTH_LONG).show();
}
}
});
populate();
}
public void delete() {
if (current != null)
{
db.open();
db.deleteTitle(current);
Toast.makeText(getApplicationContext(), "CURRENT IS:" +current, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Title deleted", Toast.LENGTH_SHORT).show();
db.close();
}
}
private void populate() {
db.open();
Cursor fetchInfo = db.fetchAllRecords();
startManagingCursor(fetchInfo);
// Create an array to specify the fields we want to display in the list (TITLE,YEAR)
String[] from = new String[]{DBAdapter.KEY_TITLE, DBAdapter.KEY_YEAR};
// an array of the views that we want to bind those fields to (in this case text1,text2,text3)
int[] to = new int[]{R.id.text1, R.id.text2};
// Now create a simple cursor adapter and set it to display
ListView lv = (ListView) findViewById(R.id.listView1);
SimpleCursorAdapter aa = new SimpleCursorAdapter(MylistTab.this, R.layout.mylistview, fetchInfo, from, to);
lv.setAdapter(aa);
lv.setDividerHeight(5);
db.close();
}
}
// activity.main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost">
<LinearLayout
android:id="#+id/LinearLayout01"
android:orientation="vertical"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<TabWidget
android:id="#android:id/tabs"
android:layout_height="wrap_content"
android:layout_width="fill_parent">
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</FrameLayout>
</LinearLayout>
</TabHost>
// mylist.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="15dp"
android:layout_marginTop="15dp"
android:text="#string/remove" />
<ListView
android:id="#+id/listView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/remove" >
</ListView>
</RelativeLayout>
// mylistview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="16dp"
android:textStyle="bold" />
<TextView
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="12dp"
android:textStyle="italic" />
</LinearLayout>
// search.xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<EditText
android:id="#+id/searchstring"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:ems="10"
android:gravity="center_vertical"
android:inputType="textAutoComplete" >
</EditText>
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/searchstring"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="#string/search" />
<ListView
android:id="#+id/listView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/search"
android:layout_marginTop="20dp"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
</ListView>
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/listView1"
android:layout_alignParentLeft="true"
android:text="#string/addTitle" />
<Button
android:id="#+id/similar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/listView1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/search"
android:text="#string/similar" />
</RelativeLayout>
Now, why cant I place an intent at searchtab in the method similar() (or earlier) where I get the ID and positive of it since im using it to populate mylist like:
There I get the ID by this code:
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
Map<String, String> s = data.get((int) id);
current = s.toString();
And then just beneath it do like this:
Intent i = new Intent(MylistTab.this, SearchTab.class);
i.putExtra("var1", current);
startActivity(i);
And in the next acitvity:
current = getIntent().getExtras().getString("var1");
Why is this not possible? When i do like this and run the app delete wont work saying there is a nullpointexception somewhere in mylisttab and i will get transferred around the layouts(which i dont want).
Has it to do with intent-filters? Im not sure I have to use them in this scenario.
Glad to hear you are embarking the Android world. Let me start by saying it is fascinating.
Answering your question, may I ask if you have any constraints for your homework? I see you have hard coded your inputs in the java files. You can (and i recommend) defining all of your screen widgets (buttons, inputs, images, etc) in a xml layout and inflate them on activity's onCreate method.
Example taken from Ioshed (Google IO app)
XML (my_activity.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView android:id="#+id/choose_account_intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp" />
</LinearLayout>
Java (MyActivity.java)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_activity);
}
Also, you could use the Fragments API which, to my understanding, is the correct way to make apps nowadays. Fragments help you modularize parts of your app's ui and behavior by creating small compoments that can be link via an activity.
Hope it helps.

Send ListView results via Messaging application

I am very new to programming. I have an app that has several views. The Main view shows a list such as Breakfast, Lunch & Dinner. When a an item is selected, example Lunch, a list of lunch menu items is displayed such as Hamburger, Cheeseburger, French Fries... (this list is created from the string-array lunch_menu that is stored in \values\lunch.xml) as the user selects the items they want, it is stored in a new array called myNewList and is displayed whe the users presses the lunchList button. All of the items are displayed that the user selected. So far, So good. I created a android:onClick="shareMyList" in the selecteditems.xml and the button works, but does not populate my list. I think what i need is to some how convert it to a string, this is where I need help.
Here is my Problem now.... I have my Share button, that when pressed, I would like it to automatically open the default Messaging app and populate the list from the selected items ListView.
package com.mycompany.lunch;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class LunchListMenu extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maincoarse);
final ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.lunch_menu,android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
final ArrayList<String> myNewList = new ArrayList<String>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String item=lv.getItemAtPosition(arg2).toString();
String itemordered;
itemordered = item + " added to list";
Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_SHORT).show();
myNewList.add(item);
}
});
// List View Button
Button btnLunchList = (Button) findViewById(R.id.lrList);
btnLunchList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.selecteditems);
ListView selecteditems = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> newadapter = new ArrayAdapter<String>(LunchListMenu.this, android.R.layout.simple_list_item_1, myNewList);
selecteditems.setAdapter(newadapter);
}
});
}
public void shareMyList(View v){
// Share Selected Items Button
Button btnShareItems = (Button) findViewById(R.id.shareMyList);
btnShareItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
share.putExtra(Intent.EXTRA_TEXT, "I'm being sent!!");
startActivity(Intent.createChooser(share, "Share Text"));
}
});
}
}
Here is the Lunch Menu Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/main_background"
android:paddingLeft="10.0dip"
android:paddingTop="0.0dip"
android:paddingRight="10.0dip"
android:paddingBottom="10.0dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/lrList"
android:layout_width="72dip"
android:layout_height="72dip"
android:layout_gravity="right"
android:background="#drawable/list" />
<ImageView
android:id="#+id/LunchMenuTitle"
android:contentDescription="#string/LunchMenu"
android:layout_width="0dip"
android:layout_height="72dip"
android:layout_weight="0.96"
android:background="#drawable/lunch"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="10.0dip"
android:background="#drawable/head"
android:orientation="horizontal" />
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#FFCC00"
android:dividerHeight="2dp" >
</ListView>
<LinearLayout
android:orientation="horizontal"
android:background="#drawable/head"
android:layout_width="fill_parent"
android:layout_height="10.0dip" />
</LinearLayout>
And Here is my selecteditems.xml Layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#drawable/main_background"
android:paddingLeft="10.0dip"
android:paddingTop="0.0dip"
android:paddingRight="10.0dip"
android:paddingBottom="10.0dip"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/shareMyList"
android:layout_width="72dip"
android:layout_height="72dip"
android:layout_gravity="right"
android:onClick="shareMyList"
android:background="#drawable/share" />
<ImageView
android:id="#+id/selectedItemsTitle"
android:contentDescription="#string/LunchTitle"
android:layout_width="0dip"
android:layout_height="72dip"
android:layout_weight="0.96"
android:background="#drawable/title"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="10.0dip"
android:background="#drawable/head"
android:orientation="horizontal" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#FFCC00"
android:dividerHeight="2dp"
android:padding="10dip"
android:textColor="#ffffff"
android:textSize="20dip"
android:textStyle="bold" />
</LinearLayout>
This may be the most kludgiest way of doing this, but it works.
package com.mycompany.lunch;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class LunchListMenu extends Activity {
String itemsordered;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maincoarse);
final ListView lv=(ListView)findViewById(R.id.listView1);
ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, R.array.lunch_menu,android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
final ArrayList<String> myNewList = new ArrayList<String>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String item=lv.getItemAtPosition(arg2).toString();
String itemordered;
itemordered = item + " added to list";
Toast.makeText(getApplicationContext(), itemordered, Toast.LENGTH_SHORT).show();
myNewList.add(item);
}
});
// List View Button
Button btnLunchList = (Button) findViewById(R.id.lrList);
btnLunchList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.selecteditems);
ListView selecteditems = (ListView) findViewById(android.R.id.list);
ArrayAdapter<String> newadapter = new ArrayAdapter<String>(LunchListMenu.this, android.R.layout.simple_list_item_1, myNewList);
selecteditems.setAdapter(newadapter);
// Get sdCard location so we can Create Dir and File
File sdCard = Environment.getExternalStorageDirectory();
File lunch = new File(sdCard,"Lunch");
lunch.mkdirs();
File file = new File(lunch, "Lunch.txt");
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(file));
} catch (IOException e) {
e.printStackTrace();
}
// Write each string in the array
StringBuilder text = new StringBuilder();
for (String s : myNewList) {
out.println(s);
}
out.close();
// read File
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append(',');
text.append(' ');
}
}
catch (IOException e) {
}
itemsordered = text;
}
});
}
public void shareMyList(View v){
// Share Selected Items Button
Button btnShareItems = (Button) findViewById(R.id.shareMyList);
btnShareItems.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", itemsordered);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
}
});
}
}

Categories

Resources