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);
}
Related
I am new Android Developer. I have not attended any Class but i am learning it myself using Internet.
Please Copy Paste the same in your android, Try it and guide me why it is not working??
it is developed in eclipse. External dependencies are httpclient-4.0.jar and httpcore-4.0.1.jar
I have developed an application.
It gets report list from IIS server. which actually links of HTML Pages. (it is global, you may please check the links)
IT has total 16 Html Pages.
Application is suppose to change Report(Html Page) in WebView every 10 seconds. It changes Report Once. but later it doesn't change.
Please check and tell me what is error.
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.CorpoServe.bvgindialtd.ReportViewer" >
<Button
android:id="#+id/btnPrev"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/prev" />
<Button
android:id="#+id/btnNext"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="#string/next" />
<WebView
android:id="#+id/Brz"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignLeft="#+id/btnPrev"
android:layout_below="#+id/btnPrev" />
<ToggleButton
android:id="#+id/tbX"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:checked="true"
android:text="#string/play"
android:textOff="Pause"
android:textOn="Play" />
</RelativeLayout>
This is my Class
package com.CorpoServe.bvgindialtd;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class ReportViewer extends ActionBarActivity {
List<String> ls= new ArrayList<String>();
int counter=0;
Handler hnd;
ToggleButton tb;
WebView bz;
public String GetIntenetData(String URL) throws Exception{
BufferedReader in=null;
String data=null;
//URL="http://corposerve.com/ActionPage.asp?action=auth&uid=abc&pwd=abc";
try{
HttpClient cl= new DefaultHttpClient();
URI ws= new URI(URL);
HttpGet rq=new HttpGet();
rq.setURI(ws);
HttpResponse rs = cl.execute(rq);
in= new BufferedReader(new InputStreamReader(rs.getEntity().getContent()));
StringBuffer sb=new StringBuffer("");
String l ="";
String nl= System.getProperty("line.separator");
while((l=in.readLine())!=null){
sb.append(l+nl);
}
in.close();
data=sb.toString();
return data;
} finally {
if(in!=null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_viewer);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
try {
String Url="http://203.90.76.206/newmis/GetReportList.aspx";
String ss[]=GetIntenetData(Url).split(System.getProperty("line.separator"));
ls.clear();
for(String s:ss){
String[] x =s.split(Pattern.quote("*"));
ls.add("http://203.90.76.206/newmis" + x[0]);
}
bz= (WebView) findViewById(R.id.Brz);
bz.getSettings().setBuiltInZoomControls(true);
bz.getSettings().setSupportZoom(true);
bz.getSettings().setUseWideViewPort(true);
bz.getSettings().setLoadWithOverviewMode(true);
bz.loadUrl(ls.get(0));
tb=(ToggleButton)findViewById(R.id.tbX);
counter=0;
hnd=new Handler();
Runnable rnbl=new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(10000);
} catch (Exception e) {
// TODO: handle exception
}
hnd.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
if (tb.isChecked()){
counter++;
if (counter>=ls.size()-1){
counter=0;
}
bz.loadUrl(ls.get(counter));
}
}
});
}
};
new Thread(rnbl).start();
} catch (Exception e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Toast t= new Toast(getApplicationContext());
t.setText( "1:" + e.getMessage());
t.show();
}
final Button nxt= (Button)findViewById(R.id.btnNext);
final Button prv=(Button)findViewById(R.id.btnPrev);
nxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
if(counter>=ls.size()){counter=0;}
bz.loadUrl(ls.get(counter));
}
});
prv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
if (counter<0){counter=ls.size()-1;}
bz.loadUrl(ls.get(counter));
}
});
tb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(tb.isChecked()){nxt.setEnabled(false);prv.setEnabled(false);}else{nxt.setEnabled(true);prv.setEnabled(true);}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.report_viewer, menu);
//MenuItem itm=menu.findItem(R.menu.report_viewer);
//itm.setVisible(false);
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);
}
}
I have to admit I haven't tried your code but there are already a bunch of things you should take care of. First, you shouldn't call your GetIntenetData() [sic] method from your Activity's onCreate(). This blocks your UI thread, and it shouldn't.
Here are some useful resources for a beginner:
Activity lifecycle: https://developer.android.com/guide/components/activities.html
Processes and Threads: https://developer.android.com/guide/components/processes-and-threads.html (as explained there, using AsyncTask is generally a good way to do work in the background, such as loading web contents)
Basically you should initialize your activity and the view components in onCreate(), then you can launch an AsyncTask from onResume() to load your content in the background.
Finally, from quickly reading your code it seems that you are only calling your Runnable once, which would explain why you are only loading one page.
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"
I have a 2 activities with edittexts on them the first activity work fine but the second activity's EditText is focused but I can't edit it nor can I click the button on it.
Also everything works in the emulator but not when I install it on the device. (The keyboard popup also does not come up in the second activity where as it does in the first activity)
Below is the code for the1st and second activity
First Activity Class
package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
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.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginActivity extends ActionBarActivity {
EditText edtEmail, edtPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Initialize components
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtPassword = (EditText) findViewById(R.id.edtPassword);
Button btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (edtEmail.getText().toString().length() > 0 && edtPassword.getText().toString().length() > 0) {
new GetAllCustomerTask().execute(new ConnecterClass());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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);
}
// Connect to the DB
private class GetAllCustomerTask extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].usrLogin(edtEmail.getText().toString(), edtPassword.getText().toString());
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
JSONObject json = null;
try {
json = jsonArray.getJSONObject(0);
if (edtEmail.getText().toString().equals(json.getString("email"))) {
if (edtPassword.getText().toString().equals(json.getString("pass"))) {
Toast toast = Toast.makeText(getApplicationContext(), "login successful", Toast.LENGTH_SHORT);
toast.show();
Intent intent = new Intent(LoginActivity.this, SearchActivity.class);
//Pass the school_id
intent.putExtra("SCHOOL_ID", json.getInt("school_id"));
startActivity(intent);
} else {
Toast toast = Toast.makeText(getApplicationContext(), "password incorrect", Toast.LENGTH_SHORT);
toast.show();
}
} else {
Toast toast = Toast.makeText(getApplicationContext(), "failed to login ...", Toast.LENGTH_SHORT);
toast.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
Second Activity Class
> package com.rohan.rohan_pc.sportappnew;
import android.content.Intent;
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.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SearchActivity extends ActionBarActivity {
EditText edtFName, edtLName, edtIDNum;
ListView listViewSearch;
String sFName, sLName, sIDNum;
int school_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
edtFName = (EditText) findViewById(R.id.edtFirstName);
edtLName = (EditText) findViewById(R.id.edtLastName);
edtIDNum = (EditText) findViewById(R.id.edtIDNum);
Button btnSearch = (Button) findViewById(R.id.btnSearch);
listViewSearch = (ListView) this.findViewById(R.id.listViewSearch);
//Initialize the default values for the search criteria variables
sFName = "";
sLName = "";
sIDNum = "";
//Load school_id
school_id = getIntent().getExtras().getInt("SCHOOL_ID");
if(edtFName.requestFocus()) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); }
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtFName.getText().toString().length() > 0)
{
sFName = edtFName.getText().toString().trim();
}
if(edtLName.getText().toString().length() > 0)
{
sLName = edtLName.getText().toString().trim();
}
if(edtIDNum.getText().toString().length() > 0)
{
sIDNum = edtIDNum.getText().toString().trim();
}
new SearchAllCustomers().execute(new ConnecterClass());
}
});
}
#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);
}
//Search in the background
public void setListViewArray(final JSONArray jsonArray)
{
this.listViewSearch.setAdapter(new Search_ListView_Adapter(jsonArray, this));
//Setup what happens when a user clicks on a searched item
this.listViewSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
JSONObject clickedItem = jsonArray.getJSONObject(position);
Intent askActivity = new Intent(getApplicationContext(), AskActivity.class);
askActivity.putExtra("IDNUM", clickedItem.getString("idnum"));
askActivity.putExtra("SCHOOL_ID", clickedItem.getInt("school_id"));
startActivity(askActivity);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
// Connect to the DB
private class SearchAllCustomers extends AsyncTask<ConnecterClass, Long, JSONArray>
{
#Override
protected JSONArray doInBackground(ConnecterClass... params) {
// Execute in background
return params[0].searchPlayers(school_id, sFName, sLName, sIDNum);
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
if (jsonArray != null) {
setListViewArray(jsonArray);
//login(edtEmail.getText().toString(),""
/*
//Got to second screen if login is successful
Intent intent = new Intent(LoginActivity.this, AfterLogin.class);
//Pass the table name through
intent.putExtra("CLIENT_DB", clientDB);
startActivity(intent);
*/
}
}
}
}
The XML - First 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"
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=".LoginAcivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/edtEmail"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:hint="email ..."
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/edtPassword"
android:layout_below="#+id/edtEmail"
android:layout_centerHorizontal="true"
android:layout_marginTop="44dp"
android:hint="password ..."
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btnLogin"
android:layout_below="#+id/edtPassword"
android:layout_centerHorizontal="true"
android:layout_marginTop="49dp" />
</RelativeLayout>
The XML - Second 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"
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="com.rohan.rohan_pc.sportsappv001.SearchActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Search"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Name"
android:ems="10"
android:id="#+id/edtFirstName"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:hint="Surname"
android:ems="10"
android:id="#+id/edtLastName"
android:layout_below="#+id/edtFirstName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/edtIDNum"
android:hint="ID Number"
android:layout_below="#+id/edtLastName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/edtLastName"
android:layout_alignEnd="#+id/edtLastName" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btnSearch"
android:layout_below="#+id/edtIDNum"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="64dp"
android:layout_marginTop="42dp" />
<ListView
android:layout_width="wrap_content"
android:layout_height="200dp"
android:id="#+id/listViewSearch"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#+id/edtIDNum"
android:layout_alignTop="#+id/edtFirstName"
android:clickable="true"
/>
I just figured to re-create the app. I dont think it is a wise decision to copy the raw files to another directory and use that.
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.
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>