Android how to load image from url and put it on top - android

Actually I have done the "load from url" part but the result is not satisfying.
I wnat the image placed on the top. However, when it loaded the image, it automatically align to center but I have declared android:layout_alignParentTop="true" .
Besides, I'd like to have some text on the image but the text are always on the top left corner..........
here are my codes:
(xml)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/list_detail"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="#+id/product_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:src="#drawable/white" />
<TextView
android:id="#+id/product_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_image"
android:text="#string/hello_world" />
<TextView
android:id="#+id/product_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/product_price"
android:text="#string/hello_world" />
</RelativeLayout>
activity:
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
public class PostDetail extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_detail);
getActionBar().setDisplayHomeAsUpEnabled(true);
WPTemplateDB dpOpener = new WPTemplateDB(this);
SQLiteDatabase db = dpOpener.getReadableDatabase();
//Log.d("passed pid", getIntent().getStringExtra("pid")+"");
Cursor cursor = db.query(WPTemplateDB.PRODUCT_TABLE,
new String[]{WPTemplateDB.TITLE, WPTemplateDB.IMAGE, WPTemplateDB.PRICE},
WPTemplateDB.PRODUCT_ID+"=?",
new String[]{getIntent().getStringExtra("pid")},
null, null, null);
String title = "", price = "", img = "";
while (cursor.moveToNext()){
title = cursor.getString(0);
img = cursor.getString(1);
price = cursor.getString(2);
}
Log.d("title", title);
Log.d("img_src", img);
TextView productTitle = (TextView)findViewById(R.id.product_title);
ImageView productImage = (ImageView)findViewById(R.id.product_image);
TextView productPrice = (TextView)findViewById(R.id.product_price);
new LoadImageFromURL(productImage).execute(img);
productTitle.setText(Html.fromHtml(title),TextView.BufferType.SPANNABLE);
productPrice.setText(price);
}
private class LoadImageFromURL extends AsyncTask<String, Void, Bitmap>{
ImageView bitmapImgView;
public LoadImageFromURL(ImageView bmImgView){
bitmapImgView = bmImgView;
}
#Override
protected Bitmap doInBackground(String... params) {
// TODO Auto-generated method stub
String urlStr = params[0];
Bitmap img = null;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(urlStr);
HttpResponse response;
try {
response = (HttpResponse)client.execute(request);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(entity);
InputStream inputStream = bufferedEntity.getContent();
img = BitmapFactory.decodeStream(inputStream);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return img;
}
#Override
protected void onPostExecute(Bitmap bitmap){
bitmapImgView.setImageBitmap(bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list_post, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpTo(this,
new Intent(this, ListPost.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}

You should use wrap_content instead match_parent for product_image's android:layout_width, and you should use FrameLayout if you want put text on the ImageView. like:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:src="#drawable/ic_launcher"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:text="test"
android:layout_height="wrap_content" />
</FrameLayout>

Related

Android ArrayAdapter onclick item

I have created a custom arrayadapter, that causes me the list of elements from a request "get" from soundcloud, but when I click on one of the elements gives me this message:
D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
here is my code:
Activity
package com.giuseppemorra.domusic;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
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.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpGet;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.impl.client.HttpClients;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import cz.msebera.android.httpclient.util.EntityUtils;
public class Second extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
Adapter adapter;
ListView lista;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onStart(){
super.onStart();
Bundle extras = getIntent().getExtras();
if (extras != null) {
String musica = extras.getString("musica");
String ric = musica;
new Mod().execute(ric);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private class Mod extends AsyncTask<String, Integer, String> {
protected String doInBackground(String... parametri) {
String par = Arrays.toString(parametri);
par = par.replace("[", "");
par = par.replace("]", "");
String[] risultati = par.split(",");
String musica = risultati[0];
Log.d("cell", musica);
HttpClient httpclient = HttpClients.createDefault();
HttpGet httppost = new HttpGet();
String gio = "";
try {
URI website = new URI("http://api.soundcloud.com/tracks/?client_id=4ee809712e980dfc07b9e8af6f42d434&limit=200&&q="+URLEncoder.encode(musica,"UTF-8"));
httppost.setURI(website);
HttpResponse response = httpclient.execute(httppost);
BufferedReader in = new BufferedReader(new InputStreamReader( response.getEntity().getContent()));
String line = in.readLine();
Log.d("Risposta dal server", line);
gio = line;
} catch (IOException | URISyntaxException b) {
b.printStackTrace();
b.printStackTrace();
}
return gio;
}
protected void onProgressUpdate(String... progress) {
}
protected void onPostExecute(String result) {
String str = result;
Log.d("new",str);
JSONArray jArrayObject;
try {
jArrayObject = new JSONArray(str);
String[] datiFin = new String[jArrayObject.length()];
String[] titleFin = new String[jArrayObject.length()];
String[] durataFin = new String[jArrayObject.length()];
String[] avatar_urlFin = new String[jArrayObject.length()];
for (int i = 0; i<jArrayObject.length(); i++) {
String stream = jArrayObject.getJSONObject(i).getString("stream_url").toString();
String id = jArrayObject.getJSONObject(i).getString("id").toString();
String title = jArrayObject.getJSONObject(i).getString("title").toString();
String durata = jArrayObject.getJSONObject(i).getString("duration").toString();
JSONObject jObj = new JSONObject(jArrayObject.getJSONObject(i).getString("user").toString());
String avatar_url = jObj.getString("avatar_url").toString();
datiFin[i] = stream.concat(",").concat(id);
titleFin[i] = title;
int minutes = (int) ((Integer.parseInt(durata) / (1000*60)) % 60);
String durataFinale = minutes+" Minuti";
durataFin[i] = durataFinale;
avatar_urlFin[i] = avatar_url;
}
lista = (ListView)findViewById(R.id.musica_lista);
lista.setFastScrollEnabled(true);
adapter = new com.giuseppemorra.domusic.Adapter(Second.this,titleFin,datiFin,durataFin,avatar_urlFin);
lista.setAdapter((ListAdapter) adapter);
lista.setOnItemClickListener(new OnItemClickListener(){
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> parent, View v, int position,long id) {
Log.d("ciao","ciao");
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
ArrayAdaptery:
package com.giuseppemorra.domusic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class Adapter extends ArrayAdapter<String> {
String[] titolo, dati, durata, avatar;
Context context;
Holder holder;
public Adapter(Context context, String[] titolo, String[] dati, String[] durata, String[] avatar) {
super(context, R.layout.lista_musica, titolo);
// TODO Auto-generated constructor stub
this.titolo = titolo;
this.avatar = avatar;
this.durata = durata;
this.dati = dati;
this.context = context;
}
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
holder = new Holder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.lista_musica, null, true);
holder.titoloMod = (TextView) view.findViewById(R.id.titoloMusica);
holder.avatarMod = (ImageView) view.findViewById(R.id.immagieMusica);
holder.durataMod = (TextView) view.findViewById(R.id.durataMusica);
holder.contMod = (TextView) view.findViewById(R.id.contDati);
holder.titoloMod.setText(titolo[position]);
holder.durataMod.setText(durata[position]);
holder.contMod.setText(dati[position]);
Picasso.with(context).load(avatar[position]).into(holder.avatarMod);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
return view;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
class Holder {
TextView titoloMod, durataMod, contMod;
ImageView avatarMod;
}
ListView:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.giuseppemorra.domusic.Second"
tools:showIn="#layout/second_bar_main"
android:focusable="false"
android:clickable="false">
<ListView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/musica_lista"
android:scrollingCache="false"
android:smoothScrollbar="true"
android:clickable="true" />
</LinearLayout>
Single item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:clickable="true" >
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/immagieMusica"
android:layout_margin="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/titoloMusica"
android:layout_alignTop="#+id/immagieMusica"
android:layout_toEndOf="#+id/immagieMusica"
android:textSize="10dp"
android:textIsSelectable="false" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/durataMusica"
android:layout_alignBottom="#+id/immagieMusica"
android:layout_toEndOf="#+id/immagieMusica" />
<EditText
android:layout_width="0dp"
android:layout_height="0dp"
android:id="#+id/contDati"
android:layout_above="#+id/durataMusica"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Then I would understand where I'm wrong, and how to perform the function qaundo you click on one of the list elements

Toast not showing for Custom List View

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.

My HttpPost don't send data. What is wrong?

I'm making a new HttpPost app, but it doesn't send data to webpage post.php.
What am I making wrong?
What is wrong in my code?
MainActivity.java
package com.pixelayer.httppost.httppost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.opengl.Visibility;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private EditText value;
private Button btn;
private ProgressBar pb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value=(EditText)findViewById(R.id.editText1);
btn=(Button)findViewById(R.id.button1);
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
btn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(value.getText().toString().length()<1){
// out of range
Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
}else{
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(value.getText().toString());
}
}
private class MyAsyncTask extends AsyncTask<String, Integer, Double>{
#Override
protected Double doInBackground(String... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result){
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public void postData(String valueIWantToSend) {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/post.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "3"));
nameValuePairs.add(new BasicNameValuePair("name", "test"));
nameValuePairs.add(new BasicNameValuePair("site", "test"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
#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);
}
}
ActivityMain.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Enter Something Below:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:ems="10"
android:hint=""
>
<requestFocus />
</EditText>
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="24dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignRight="#+id/editText1"
android:layout_below="#+id/progressBar1"
android:layout_marginTop="24dp"
android:text="Submit" />
</RelativeLayout>
HttpResponse response = httpclient.execute(httppost);
This line is most likely throwing an exception, and you are ignoring all of your exceptions. Try logging them via adb like so:
try {
//...
} catch (ClientProtocolException e) {
Log.d("MYAPP", e.getMessage(), e);
} catch (IOException e) {
Log.d("MYAPP", e.getMessage(), e);
}

Unable to set ListView Divider color in Android

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"

Items in listView have white text when using setAdapter in UI thread

For another listView in another activity the text color of the items is black, like it should be. However, in another activity when using setAdapter in a new thread when the new items created the text color is white when I want it black. Here is the contents of Layout and Java code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="project.yemeb.Search"
android:background="#ffffffff">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:background="#drawable/back_web"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:id="#+id/relativeLayout"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/button2"
android:background="#ffffffff"
android:onClick="onBtnClick"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:layout_alignBottom="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#ffffffff"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2"
android:layout_alignTop="#+id/button2" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_alignParentBottom="true"
android:layout_below="#+id/relativeLayout"
android:headerDividersEnabled="false" />
</RelativeLayout>
Java code:
package project.yemeb;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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 java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class Search extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
((EditText) findViewById(R.id.editText)).setText(message);
final String url = "http://example.com/sql.php?keyword="+((EditText) findViewById(R.id.editText)).getText().toString()+"&mode=6";
new Thread() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(url));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
response.getEntity().writeTo(out);
out.close();
} catch (IOException e) {
}
String responseString = out.toString();
String[] list = responseString.split("\\|");
for(String f : list)
{
((MyApplication)getApplication()).setSearches(f);
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, ((MyApplication)getApplication()).getSearches());
runOnUiThread(new Runnable() {
#Override
public void run() {
((ListView) findViewById(R.id.listView)).setAdapter(adapter);
}
});
((ListView) findViewById(R.id.listView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent intent = new Intent(getApplicationContext(), List.class);
intent.putExtra("message", ((String) ((ListView) findViewById(R.id.listView)).getItemAtPosition(arg2)));
startActivity(intent);
}
});
//..more logic
} else {
//Closes the connection.
try {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
} catch (IOException e) {
}
}
}
catch (ClientProtocolException e)
{
}
catch (IOException e)
{
}
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.search, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
How do I solve this problem? There were no errors that occurred.
You shouldn't be doing getApplicationContext(), instead try using Search.this.

Categories

Resources