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.
Related
I have created a clickable ListView with a TextView on the new page. I would like to display JSON data in this TextView, and I want the JSON data to be retrieved by clicking the ListView item i.e. opening the new page. Is this possible?
Below you will find the code I have so far. The ListView is clickable and functions correctly, but the JSON code does not.
If you know the solution to my problem, you're a superstar! Thank you in advance.
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
String[] names = {
"A",
"B"
};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_view, names);
listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Searching " + names[position], Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putExtra("names", names[position]);
startActivity(intent);
}
public void onClick(View view) {
try {
JSONArray reader = new JSONArray(readJSONFromAsset());
ListView tvData = (ListView) findViewById(R.id.listview);
TextView tvContext = (TextView) findViewById(R.id.detail);
String codeArray = tvData.getAdapter().toString();
for (int x = 0; x < reader.length(); x++) {
JSONObject Array = reader.getJSONObject(x);
String data = Array.getString("data");
String context = Array.getString("context");
if (data.equals(codeArray)) {
tvContext.setText(context);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String readJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</android.support.constraint.ConstraintLayout>
DetailActivity.java
package com.example.steen.array;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
TextView textView = (TextView)findViewById(R.id.detail);
textView.setText(getIntent().getStringExtra("names"));
}
}
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DetailActivity">
<TextView
android:id="#+id/detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.constraint.ConstraintLayout>
list_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</TextView>
data.json
[
{
"data": "A",
"context": "(A) if you see this, JSON is working"
},
{
"data": "B",
"context": "(B) if you see this, JSON is working"
}
]
I am writing application that will fetch json array from website. That json array includes Title, Description and image. I write code and custom list view adapter. List is showing but now I need to show toast in order to get which list item is clicked. I tried alot and searched but did not get solution.
Please help.
ViewCampaigns.java (Treated as Main.java)
package com.therightsol.saveasoul.saveasoul;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
public class viewcampaigns extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
private ProgressBar progress;
ListView lv = null;
MyData arrData[] = null;
ArrayList<String> arrlist = null;
// url to get all products list
private static String url_all_campaigns = "http://therightsol.com/saveasoul125/mobile/get_all_campaigns_jsonArr";
private AlertDialog alert;
// products JSONArray
String response = "";
JSONArray jsonArr = null;
ArrayAdapter<String> campaignAdapter;
ListAdapter la;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campaigns);
progress = (ProgressBar) findViewById(R.id.progressBar1);
lv = (ListView) findViewById(R.id.listView);
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
// Loading campaigns in Background Thread
LoadAllCampaigns task = new LoadAllCampaigns();
task.execute();
}else {
/*new AlertDialog.Builder(viewcampaigns.this)
.setTitle("Your Alert")
.setMessage("Your Message")
.setCancelable(false)
.setPositiveButton("ok", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Whatever...
}
}).create().show();*/
}
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String t = (String) la.getItem(position);
Toast.makeText(getApplicationContext(),"HIIII", Toast.LENGTH_SHORT).show();
}
});
}
class MyData{
public String imgpath;
public String title;
public String shrtdes;
public MyData(){
super();
}
public MyData(String path, String t, String desc){
this.imgpath = path;
this.title = t;
this.shrtdes = desc;
}
}
/**
* Background Async Task to Load all campaigns by making HTTP Request
* */
class LoadAllCampaigns extends AsyncTask<String, Void, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
//Log.i("save a soul", "I am in preexecute.");
super.onPreExecute();
pDialog = new ProgressDialog(viewcampaigns.this);
pDialog.setMessage("Loading Campaigns. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All campaigns from url
* */
protected String doInBackground(String... params) {
Log.i("save a soul", "I am in doinbackground");
//http post
try{
//System.out.println("The output of : doInBackground " +params[0]);
URL url = new URL(url_all_campaigns);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
System.out.println("The output of getResponsecode: " + conn.getResponseCode());
conn.connect();
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
return response;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
pDialog.hide();
// updating UI from Background Thread
Log.i("Save Test", s);
try {
jsonArr = new JSONArray(response);
int l = jsonArr.length();
arrData = new MyData[l];
for (int i = 0; i < jsonArr.length(); i++)
{
JSONObject jsonObj = jsonArr.getJSONObject(i);
System.out.println(jsonObj);
String path = String.valueOf(jsonObj.getString("campaign_image_path"));
String title = String.valueOf(jsonObj.getString("campaign_title"));
String shrtdes = String.valueOf(jsonObj.getString("campaign_short_description"));
path = "http://therightsol.com/saveasoul125/" + path;
Log.i("save a soul", "I am in onPostExecute");
arrData[i] = new MyData(path, title, shrtdes);
}
la = new campaigns_customAdapter(viewcampaigns.this, R.layout.campaignslist, arrData );
/*ListAdapter la = new campaigns_customAdapter(
viewcampaigns.this, title, camp
);*/
lv.setAdapter(la);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String t = (String) la.getItem(position);
Toast.makeText(getApplicationContext(),position, Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
campaigns custom adapter
package com.therightsol.saveasoul.saveasoul;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class campaigns_customAdapter extends ArrayAdapter<viewcampaigns.MyData> {
viewcampaigns.MyData [] obj;
Context context;
int resourse;
public campaigns_customAdapter(Context context, int resource, viewcampaigns.MyData[] objects) {
super(context, resource, objects);
this.context=context;
this.resourse=resource;
this.obj=objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(getContext());
//View v = inflater.inflate(R.layout.campaignslist, parent, false);
View row=inflater.inflate(resourse,parent,false);
// Getting Views
TextView title = (TextView) row.findViewById(R.id.campaignTitle);
TextView shrtDesc = (TextView) row.findViewById(R.id.shortDescription);
ImageView campaignimg = (ImageView) row.findViewById(R.id.campaignimage);
title.setText( obj[position].title );
shrtDesc.setText( obj[position].shrtdes);
// Inflating Image
try {
URL url = new URL(obj[position].imgpath);
new DownloadImageTask(campaignimg)
.execute(url.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
return row;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Activity Campaign .xml (XML file that has a list view)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="10"
android:padding="4dip" >
</ProgressBar>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
</RelativeLayout>
Campaign list (XML for Custom Layout of list item)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/campaignimage"
android:backgroundTintMode="src_over"
android:clickable="false"
android:cropToPadding="false"
android:layout_alignTop="#+id/campaignTitle"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:maxLength="4"
android:ellipsize="end"
android:layout_marginBottom="0dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Title"
android:id="#+id/campaignTitle"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/campaignimage"
android:layout_alignEnd="#+id/campaignimage"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:capitalize="words"
android:textStyle="bold"
android:layout_marginLeft="112dp"
android:layout_marginRight="12dp"
android:layout_marginTop="6dp"
android:typeface="monospace"
android:textColor="#1f6b88"
android:textSize="16dp"
android:layout_marginBottom="4dp"
android:padding="3dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="66dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/shortDescription"
android:typeface="sans"
android:textStyle="normal"
android:textSize="12dp"
android:paddingLeft="3dp"
android:textColor="#2586a9"
android:layout_below="#+id/campaignTitle"
android:layout_alignLeft="#+id/campaignTitle"
android:layout_alignStart="#+id/campaignTitle"
android:maxLength="14"
android:ellipsize="end"
android:layout_marginRight="12dp"
android:paddingTop="2dp"
android:paddingRight="3dp"
android:paddingBottom="3dp" />
</RelativeLayout>
Instead of using getApplicationContext() in your Toast statement use ViewCampaigns.this . It should solve your problem.
I am new to java and I could use some help. In the following program, when I rotate the screen the ListView disappears. When I click back, then pull the app back up both of my TextViews and my ListView are cleared. I read up on this some and from what I gather it's because the activity basically restarts upon these actions. I looked for a good way to save the information in these cases, but nothing I tried is working. Any help would be greatly appreciated. If my code is a mess, I apologize, like I said I'm a beginner. I tried to use the onSavedInstanceState() method, but I can't get it to work. I realize it's probably some stupid mistake that I am making, but I have been at it for hours and I can't figure out what I'm doing wrong. Thanks in advance.
package dev.rogueinteractive.barcodescannershoppingcartii;
import android.app.Activity;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements OnClickListener {
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putStringArrayList("myKey", (ArrayList<String>) productReport);
}
private static final String USER_AGENT = "Mozilla/5.0";
private static String GET_URL ;
private ArrayAdapter<String> listAdapter ;
List<String> productReport = new ArrayList<String>();
public void sendGET() throws IOException {
URL obj = new URL(GET_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("GET Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
fullResponse = response.toString();
String[]responseArray = fullResponse.split("\"");
String price = new String(responseArray[30]);
price = new StringBuffer(price).insert(1, " ").toString();
price = new StringBuffer(price).insert(2, "$").toString();
responseArray[30] = price;
List<String> modifiedArray = new ArrayList<String>();
modifiedArray.add(responseArray[27]);
modifiedArray.add("\n");
modifiedArray.add("\n");
modifiedArray.add(responseArray[28]);
modifiedArray.add(responseArray[29]);
modifiedArray.add(responseArray[30]);
modifiedResponse = modifiedArray.toString();
modifiedResponse= modifiedResponse.replaceAll(",", "");
modifiedResponse = modifiedResponse.replaceAll("[\\[\\]]", "");
productReport.add(modifiedResponse);
} else {
responseTXT.setText("GET request not worked");
}
}
public String modifiedResponse;
public String fullResponse;
public String scanContent;
private Button scanBtn;
private TextView formatTxt, contentTxt, responseTXT;
public ListView mainListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
List<String> productReport = savedInstanceState.getStringArrayList("myKey");
if (productReport != null) {
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
}
}
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
mainListView = (ListView) findViewById( R.id.mainListView );
scanBtn = (Button) findViewById(R.id.scan_button);
formatTxt = (TextView) findViewById(R.id.scan_format);
contentTxt = (TextView) findViewById(R.id.scan_content);
responseTXT = (TextView) findViewById(R.id.response);
scanBtn.setOnClickListener(this);
}
public void onClick(View v) {
if (v.getId() == R.id.scan_button) {
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult.getFormatName() != null) {
this.scanContent = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanContent);
GET_URL="http://api.walmartlabs.com/v1/search?query="+scanContent+"&format=json&apiKey=5sk5b7u25b4qawku5zsm289z";
try {
sendGET();
} catch (IOException e) {
e.printStackTrace();
}
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
mainListView.setAdapter( listAdapter );
} else if (scanningResult==null){
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Main Activity
<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" >
<Button android:id="#+id/scan_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/scan" />
<TextView
android:id="#+id/scan_format"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:layout_centerHorizontal="true"
android:layout_below="#id/scan_button" />
<TextView
android:id="#+id/scan_content"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:layout_centerHorizontal="true"
android:layout_below="#id/scan_format" />
<ListView android:id="#+id/mainListView"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:layout_below="#id/scan_content"/>
<TextView
android:id="#+id/response"
android:maxLines = "10000"
android:scrollbars = "vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="true"
android:layout_centerHorizontal="true"
android:layout_below="#id/scan_content" />
</RelativeLayout>
Row Layout
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
I think you've missed two things.
First, you're not setting back your mainListView adapter to receive the list you've saved on onSaveInstanceState. Note that you're getting the myList on onCreate method, if savedInstanceState is not null, but the listView is not receiving the new adapter you're creating. I'd suggest add this on onCreate method:
...
//current code
scanBtn.setOnClickListener(this);
//New Code to be added
mainListView.setAdapter( listAdapter );
Second, if savedInstanceState is not null, you're creating a new list of productReport to receive the list you've saved before rotation, but you're using the list productReport elsewhere. You should add all items received from the bundle you've saved on this list or even recreate the list of products.
//Current code
if (savedInstanceState != null) {
List<String> productReport = savedInstanceState.getStringArrayList("myKey");
if (productReport != null) {
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
}
}
//Replaced code
if (savedInstanceState != null) {
productReport = savedInstanceState.getStringArrayList("myKey");
if (productReport != null) {
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, productReport);
}
}
Another thing: I don't think you're 100% sure about the json returned by the site you've been getting data. It's not AT ALL a good idea to retrieve data and try to get things like
String price = response[30];
because you can get easily an array out of bounds exception.
Check the GSON library, maybe you can create a model class to hold the results using something like
new Gson().fromJson(//your response string goes here, //your model class goes here)
Finally, you cannot hold the state when back button is pressed, unless you make it static or retrieve data again.
I have an activity with a ListView in it. I have set the color of ListView divider to black using android:divider="#000000" attribute and set the divider height to 1dp. For some reason the divider line is showing blue color instead of black. Here is my xml. Any help will be appreciated.
second_selection.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:background="#1A1A1A"
android:orientation="vertical"
tools:context="com.example.saregama.MainActivity" >
<FrameLayout
android:id="#+id/myframe"
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#000000" />
<include
android:id="#+id/new_tool"
layout="#layout/toolbar_actionbar_with_headerbar" />
<ImageView
android:id="#+id/loader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:src="#drawable/newloading" />
<ListView
android:id="#+id/product_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000000"
android:dividerHeight="1dp"
android:layoutAnimation="#anim/layout_bottom_to_top_slide"
android:padding="10dp"
android:text="#string/hello_world" />
</LinearLayout>
And if necessary here is my code
SecondSelection.java
package com.example.something;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class SecondSelection extends ActionBarActivity {
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CustomAdapter adapter;
ListView listProduct;
ArrayList<String> records;
Intent i;
Intent j;
Intent k;
private Toolbar toolbar;
ValueAnimator colorAnimation;
FrameLayout myframe;
ValueAnimator statusAnim;
ImageView image;
Animation anim;
BackTask bt;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second_selection);
toolbar = (Toolbar) findViewById(R.id.new_tool);
setSupportActionBar(toolbar);
myframe = (FrameLayout)findViewById(R.id.myframe);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow(); // in Activity's onCreate() for instance
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
w.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
else{
myframe.setVisibility(View.GONE);
}
context = this;
records = new ArrayList<String>();
listProduct = (ListView) findViewById(R.id.product_list);
image = (ImageView)findViewById(R.id.loader);
anim = AnimationUtils.loadAnimation(this, R.anim.myanim);
image.startAnimation(anim);
i = new Intent(this, ReportActivity.class);
j = new Intent(this, RequestActivity.class);
k = new Intent(this, AboutDeveloper.class);
bt = new BackTask();
bt.execute();
adapter = new CustomAdapter(context, R.layout.list_item_second,
R.id.pro_name, records);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
String sText = ((TextView) v.findViewById(R.id.pro_name))
.getText().toString();
Intent songIntent = new Intent(getApplicationContext(),
MainActivity.class);
songIntent.putExtra("second_selection", sText);
startActivity(songIntent);
}
});
//Animation for Action Bar
Integer colorFrom = getResources().getColor(R.color.first);
Integer colorTo = getResources().getColor(R.color.last);
colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
toolbar.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
//Animation for Status Bar
Integer colorFirst = getResources().getColor(R.color.begin);
Integer colorLast = getResources().getColor(R.color.end);
statusAnim = ValueAnimator.ofObject(new ArgbEvaluator(), colorFirst, colorLast);
statusAnim.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
myframe.setBackgroundColor((Integer)animator.getAnimatedValue());
}
});
//Start the Animations after fetching the list.
//After executing the bt.execute()
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
this.finish();
}
return super.onKeyDown(keyCode, event);
}
#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();
return super.onOptionsItemSelected(item);
}
#Override
public void onStart()
{
super.onStart();
if (bt.getStatus() == Status.FINISHED) {
doAnimation();
}
}
private void doAnimation() {
statusAnim.setDuration(800);
colorAnimation.setDuration(1300);
colorAnimation.start();
statusAnim.start(); // start animations
}
// background process to make a request to server and list product
// information
private class BackTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// pd = new ProgressDialog(context);
// pd.setTitle("Retrieving data");
// pd.setMessage("Please wait.");
// pd.setCancelable(true);
// pd.setIndeterminate(true);
// pd.show();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
records.clear();
httpclient = new DefaultHttpClient();
httppost = new HttpPost(
"");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); // close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String record = json_data.getString("alp") + "__"
+ json_data.getString("f");
records.add(record);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
// if (pd != null)
// pd.dismiss(); // close dialog
image.clearAnimation();
image.setVisibility(View.GONE);
adapter.notifyDataSetChanged();
doAnimation();// notify the ListView to get new
// records
}
}
}
Update:
This problem persists only in devices having API < 19
if nothing works, then u can create your own divider.
First remove the default divider.
android:dividerHeight="0dp"
android:divider="#null"
And then add the view in your custom_row_layout.xml
`
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="30dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:textSize="17sp"
android:textColor="#color/white" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/white" />
</LinearLayout>
`
I set up a style for ListViews, in my styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android">
...
<style name="ListViews" parent="#android:style/Widget.ListView">
<item name="android:cacheColorHint">#color/transparent</item>
<item name="android:divider">#drawable/list_divider</item>
<item name="android:dividerHeight">1px</item>
</style>
...
</resources>
My ListView uses that style as such:
style="#style/ListViews"
Obviously, I have such drawable in my drawable folder.
My list_divider.xml drawable is as such:
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<solid android:color="#color/navy_semi" />
</shape>
[EDIT]
Obviously, instead of #color/transparent and #color/navy_semi, use your own colors.
These ones are defined only in my color resurces.
Use android:background instead of android:divider
<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:background="#1A1A1A"
android:orientation="vertical"
tools:context="com.example.saregama.MainActivity" >
<FrameLayout
android:id="#+id/myframe"
android:layout_width="match_parent"
android:layout_height="25dp"
android:background="#000000" />
<include
android:id="#+id/new_tool"
layout="#layout/toolbar_actionbar_with_headerbar" />
<ImageView
android:id="#+id/loader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:src="#drawable/newloading" />
<ListView
android:id="#+id/product_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="#000000"
android:dividerHeight="1dp"
android:layoutAnimation="#anim/layout_bottom_to_top_slide"
android:padding="10dp"
android:text="#string/hello_world" />
use below attribute in your list view.
android:cacheColorHint="#null"
Would like to get what I am working on in a list view. I pulled some JSON and a bitmap off the net and as of now im have it so I can scroll through them left and right at the click of a button, but would like to place them in a list view instead.
I created the layout for the list view which is this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:padding="3dp"
android:scaleType="fitXY"
android:src="#drawable/generic" />
<TextView
android:id="#+id/Model"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_toLeftOf="#+id/price"
android:layout_toRightOf="#+id/imageView1"
android:maxLines="1"
android:text="title"
android:textColor="#android:color/black"
android:textSize="15dip"
android:textStyle="bold" />
<TextView
android:id="#+id/Price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="10dp"
android:layout_marginTop="5dip"
android:text="$$$$"
android:textColor="#android:color/holo_red_light"
android:textSize="12dip" />
<TextView
android:id="#+id/Description"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/Model"
android:layout_toRightOf="#+id/imageView1"
android:ellipsize="end"
android:maxLines="3"
android:text="desc"
android:textColor="#android:color/black"
android:textSize="13dip" />
</RelativeLayout>
</LinearLayout>
This is what i want each section of the listView to follow, and I can populate it fine with the JSON information, as well as the Bitmap.
Right here is the main Activity in which I am doing this All in:
package com.example.parsejson;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ParseJSONActivity extends Activity {
private static final String TAG = "ParseJSON";
private static final String BikeInfo = "http://www.tetonsoftware.com/bikes/bikes.json";
private static final String BikePic = "http://www.tetonsoftware.com/bikes/";
public static final int MAX_LINES = 15;
private TextView description;
private TextView model;
private TextView price;
private TextView example;
private ImageView bikePic;
private Button bleft;
private Button bright;
JSONArray jsonArray;
int numberentries = -1;
int currententry = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_parse_json);
description = (TextView) findViewById(R.id.Description);
model = (TextView) findViewById(R.id.Model);
price = (TextView) findViewById(R.id.Price);
bikePic = (ImageView) findViewById(R.id.imageView1);
bleft = (Button) findViewById(R.id.bleft);
bright = (Button) findViewById(R.id.bright);
example = (TextView) findViewById(R.id.textView4);
ConnectivityCheck myCheck = new ConnectivityCheck(this);
if (myCheck.isNetworkReachableAlertUserIfNot()) {
DownloadTask myTask = new DownloadTask(this);
myTask.execute(BikeInfo);
}
}
public void processJSON(String string) {
try {
JSONObject jsonobject = new JSONObject(string);
//*********************************
//magic number to make JSON indented
final int INDENT =2;
Log.d(TAG,jsonobject.toString(INDENT));
// you must know what the data format is, a bit brittle
jsonArray = jsonobject.getJSONArray("Bikes");
// how many entries
numberentries = jsonArray.length();
currententry = 0;
setJSONUI(currententry); // parse out object currententry
Log.i(TAG, "Number of entries " + numberentries);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setJSONUI(int i) {
StringBuilder bikePicUrl = new StringBuilder(BikePic);
if (jsonArray == null) {
Log.e(TAG, "tried to dereference null jsonArray");
return;
}
bikePicUrl.append( (i+1) + ".jpg");
String bikeString = bikePicUrl.toString();
example.setText(bikePicUrl);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Bitmap bikeImage = getBitmapFromURL(bikeString);
bikePic.setImageBitmap(bikeImage);
// gotta wrap JSON in try catches cause it throws an exception if you
// try to
// get a value that does not exist
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
description.setText(jsonObject.getString("Description"));
model.setText(jsonObject.getString("Model"));
price.setText(jsonObject.getString("Price"));
} catch (JSONException e) {
e.printStackTrace();
}
setButtons();
}
private void setButtons() {
// make sure that appropriate buttons enabled only
bleft.setEnabled(numberentries != -1 && currententry != 0);
bright.setEnabled(numberentries != -1
&& currententry != numberentries - 1);
}
public void doLeft(View v) {
if (numberentries != -1 && currententry != 0) {
currententry--;
setJSONUI(currententry);
}
}
public void doRight(View v) {
if (numberentries != -1 && currententry != numberentries) {
currententry++;
setJSONUI(currententry);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_parse_json, menu);
return true;
}
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap backgroundImage = BitmapFactory.decodeStream(input);
return backgroundImage;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
I Just am having trouble populating a list view, any help would be awesome! I tried to folow this one tutorial on list views, but since this class extends Activity, and a listView class extends ListActivity I couldn't seem to get anything to work!
You're going to want to use a custom adapter to display the data. The images will have to be done in the background since they are being loaded off of the net. Here is a very in depth tutorial for listview and adapters
http://www.vogella.com/tutorials/AndroidListView/article.html
For the image loading, or "lazy loading", there are tons of great third part libraries, such has Volley, or my favorite Universal Image Loader