Thread Stops Responding - android

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.

Related

Error while displaying records from external storage to listview

Im having problem while displaying .mp3 files from external storage to the listview. Im getting error with "ArrayAdapter requires a resource ID to be a TextView". All is set but dont know why this is happening. Below is the source code, please help me out!
"Activity_main.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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.testproject.MainActivity" >
<ListView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="#id/android:list" >
</ListView>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/android:list"
android:layout_alignParentBottom="true"
android:layout_marginBottom="43dp"
android:layout_marginLeft="20dp"
android:text="#string/stop" />
</RelativeLayout>
"list.xml"
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<GridLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/txt1"
android:layout_width="309dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</GridLayout>
</TableRow>
</TableLayout>
"MainActivity.java"
package com.example.testproject;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
class mp3filter implements FilenameFilter{
public boolean accept(File dir, String filename) {
return filename.endsWith(".mp3");
}
}
public class MainActivity extends ListActivity {
private static final String SD_PATH = new String(Environment.getExternalStorageDirectory().getPath() + "/");
private List<String> voice = new ArrayList<String>();
private MediaPlayer mp = new MediaPlayer();
Button btn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updatePlayList();
btn = (Button) this.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp.stop();
}
});
}
protected void onListItemClick(ListView list, View view, int position, long id)
{
try{
mp.reset();
mp.setDataSource(Environment.getExternalStorageDirectory() + voice.get(position));
mp.prepare();
mp.start();
}catch(IOException e)
{
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void updatePlayList() {
File home = new File(SD_PATH);
if(home.listFiles(new mp3filter()).length>0)
{
for(File file: home.listFiles(new mp3filter()))
{
voice.add(file.getName());
}
}
ArrayAdapter<String> voiceList = new ArrayAdapter<String>(this,R.layout.list,voice);
setListAdapter(voiceList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Because the ArrayAdapter<String> need an TextView to show value, you can see the implement code of ArrayAdapter getView method. However your list layout is so complicated as the input. So you can choose one of these options below:
Try to change R.layout.list to
android.R.layout.simple_list_item_1 and test again
Create
YourCustomAdapterClass extends ArrayAdapter and figure out the
TextView in getView() method. Sample from here
CreateYourCustomAdapterClass extends BaseAdapter. Sample from here
Update code:
protected void onListItemClick(ListView list, View view, int position, long id) {
try {
mp.reset();
mp.setDataSource(SD_PATH + voice.get(position));
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name), e.getMessage());
}
}
private void updatePlayList() {
File home = new File(SD_PATH);
File[] fileList = home.listFiles(new mp3filter());
if (fileList.length > 0) {
for (File file : fileList) {
voice.add(file.getName());
}
}
ArrayAdapter<String> voiceList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, voice);
setListAdapter(voiceList);
}

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);
}

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.

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

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>

Android Login Alternatives

I'm implementing various things at the moment, but the one thing that boggles me is Android Login Mechanism. I'm not so sure which login mechanism to choose from in different applications (where all of them are accessing internet).
Let's say I have two apps:
A: This app basically should connect to the server and let users chat - we can see the online user list (no roster, everybody is friend with everybody), so it's a chatting application.
B. This app should authenticate to the server and let users post messages to their WALL or something, so when the other user comes online it will instantly display those messages to him.
I'm deliberately using "connect to the server" trying to be generic, since this is what I want to know. What type of authentication should I use, so that my server knows that the user is legitimate one:
1) Custom Registration + Login: I don't want to use that, since users don't want to register another username and there are a lot of alternatives available.
2) OpenID: I should use this when I only need authenticated users, without the need to access their private information on whatever site. I'm not too fond of this, because a browser needs to open for this to work.
3) OAuth: The same as OpenID, but I can also get access to private resources of the user. Here is the same problem, a browser needs to open exchanging the keys and tokens, so it doesn't make too good user experience.
4) AccountManager: This is a very good option, but I don't like it, since it's not a part of the application. I'm not even sure what should happen when the user hits the Login button, and AccountManager pops up. Should I choose the existing account alraedy listed in the AccountManager, what if I want to choose a different account, like Yahoo, etc - can AccountManager register it, login to it, and return the application - authenticated.
I would very much like to hear the existing implementations of all of the 4 alternatives that I can use. I know there are a lot of them out there and I don't want them listed here, I know them. The only problem is that I don't know which one of them to use, that will do the work the way I want. The following is a list of things I want:
1) In the application, when user clicks the Login button, something should open letting the user choose between the following alternatives: Google, Facebook, Yahoo, Twitter. The user should login with whatever account, which should be noted as authenticated.
2) That account should then be user as an access token to authenticate to my server - so my server only accepts the token and check that it's valid.
The whole point of this is that I don't have to implement login mechanism on my server, but users are still authenticated against my server, so we can exchange some data, etc.
package com.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText login_uname, login_pwd;
TextView invalid_error;
Button login_btn;
private boolean canExit;
TextView pword_showhide;
// string login_un,login_pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
login_uname = (EditText) findViewById(R.id.login_username);
login_pwd = (EditText) findViewById(R.id.login_password);
invalid_error = (TextView) findViewById(R.id.InvalidError);
login_btn = (Button) findViewById(R.id.login_btn);
// loginbutton.setEnabled(false);
invalid_error.setVisibility(View.GONE);
pword_showhide = (TextView) findViewById(R.id.pwd_showhide);
// pword_showhide.setText("show");
pword_showhide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (login_pwd.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
login_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
pword_showhide.setText("show");
} else {
login_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
pword_showhide.setText("hide");
}
login_pwd.setSelection(login_pwd.getText().length());
}
});
checkValidation();
login_uname.addTextChangedListener(mWatcher);
login_pwd.addTextChangedListener(mWatcher);
}
private void checkValidation() {
// TODO Auto-generated method stub
if ((TextUtils.isEmpty(login_uname.getText())) || (TextUtils.isEmpty(login_pwd.getText())))
login_btn.setEnabled(false);
else {
login_btn.setEnabled(true);
}
}
public void login(View view) {
if (login_uname.getText().toString().equals("a") && login_pwd.getText().toString().equals("a")) {
invalid_error.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Login Success", Toast.LENGTH_LONG).show();
login_uname.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_username, 0, 0, 0);
login_pwd.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_password, 0, 0, 0);
//correcct password
} else {
//wrong password
invalid_error.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(), "Login fail", Toast.LENGTH_LONG).show();
login_uname.setCompoundDrawablesWithIntrinsicBounds( R.drawable.error_username, 0, 0, 0);
login_pwd.setCompoundDrawablesWithIntrinsicBounds( R.drawable.error_password,0, 0, 0);
}
}
TextWatcher mWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
checkValidation();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
#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);
}
#Override
public void onBackPressed() {
if (canExit)
super.onBackPressed();
else {
canExit = true;
Toast.makeText(getApplicationContext(), "Press again to Exit", Toast.LENGTH_SHORT).show();
}
mHandler.sendEmptyMessageDelayed(1, 2000/*time interval to next press in milli second*/);// if not pressed within 2seconds then will be setted(canExit) as false
}
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
canExit = false;
break;
default:
break;
}
}
};
}
login_screen.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"
tools:context=".LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Invalid Login Details"
android:id="#+id/InvalidError"
android:gravity="center"
android:background="#ff3a0f"
android:textColor="#FFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="50dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/login_lyt">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/login_username"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="User Name"
android:drawableLeft="#drawable/icon_username"
android:layout_marginTop="141dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="******"
android:drawableLeft="#drawable/icon_password"
android:ems="10"
android:id="#+id/login_password"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/pwd_showhide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/login_password"
android:layout_alignBottom="#+id/login_password"
android:layout_alignParentRight="true"
android:text="show" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"
android:background="#f0a422"
android:id="#+id/login_btn"
android:layout_below="#+id/login_password"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>
package com.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.PasswordTransformationMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText login_uname, login_pwd;
TextView invalid_error;
Button login_btn;
private boolean canExit;
TextView pword_showhide;
// string login_un,login_pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
login_uname = (EditText) findViewById(R.id.login_username);
login_pwd = (EditText) findViewById(R.id.login_password);
invalid_error = (TextView) findViewById(R.id.InvalidError);
login_btn = (Button) findViewById(R.id.login_btn);
// loginbutton.setEnabled(false);
invalid_error.setVisibility(View.GONE);
pword_showhide = (TextView) findViewById(R.id.pwd_showhide);
// pword_showhide.setText("show");
pword_showhide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (login_pwd.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
login_pwd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
pword_showhide.setText("show");
} else {
login_pwd.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
pword_showhide.setText("hide");
}
login_pwd.setSelection(login_pwd.getText().length());
}
});
checkValidation();
login_uname.addTextChangedListener(mWatcher);
login_pwd.addTextChangedListener(mWatcher);
}
private void checkValidation() {
// TODO Auto-generated method stub
if ((TextUtils.isEmpty(login_uname.getText())) || (TextUtils.isEmpty(login_pwd.getText())))
login_btn.setEnabled(false);
else {
login_btn.setEnabled(true);
}
}
TextWatcher mWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
checkValidation();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
#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);
}
#Override
public void onBackPressed() {
if (canExit)
super.onBackPressed();
else {
canExit = true;
Toast.makeText(getApplicationContext(), "Press again to Exit", Toast.LENGTH_SHORT).show();
}
mHandler.sendEmptyMessageDelayed(1, 2000/*time interval to next press in milli second*/);// if not pressed within 2seconds then will be setted(canExit) as false
}
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
canExit = false;
break;
default:
break;
}
}
};
}
login_screen.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"
tools:context=".LoginActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Invalid Login Details"
android:id="#+id/InvalidError"
android:gravity="center"
android:background="#ff3a0f"
android:textColor="#FFF"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="50dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/login_lyt">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/login_username"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="User Name"
android:drawableLeft="#drawable/icon_username"
android:layout_marginTop="141dp" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="******"
android:drawableLeft="#drawable/icon_password"
android:ems="10"
android:id="#+id/login_password"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:id="#+id/pwd_showhide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/login_password"
android:layout_alignBottom="#+id/login_password"
android:layout_alignParentRight="true"
android:text="show" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Login"
android:background="#f0a422"
android:id="#+id/login_btn"
android:layout_below="#+id/login_password"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="31dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</RelativeLayout>

Categories

Resources