Simple program force closing - java

I'm making a program for Android using Eclipse. Here is my code for MainAcitvity.java:
package com.example.changeme;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Button set = (Button)findViewById(R.id.set);
TextView out = (TextView)findViewById(R.id.out);
EditText in = (EditText)findViewById(R.id.input);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
set.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setcontent();
}
});
}
public void setcontent()
{
String con = in.getText().toString();
out.setText(con);
}
#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 false;
}
}
Layout for main activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
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=".MainActivity" >
<TextView
android:id="#+id/out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/set"
android:layout_alignParentBottom="true"
android:layout_marginBottom="37dp"
android:text="#string/Change"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/set"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/input"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/Set" />
<EditText
android:id="#+id/input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="37dp"
android:ems="10"
android:inputType="textPersonName" />
It crashes when I run the program on my N4.

You need to inflate your layout before retrieve your elements, otherwise findViewById will return null and hence the line set.setOnClickListener(/**/); will throw a NullPointerException which make your app crashing.
Button set;
TextView out;
EditText in;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //<-- the layout is inflated, i.e it's rendered
/******************************************************/
//Now you can retrieve your elements from this layout
set = (Button)findViewById(R.id.set);
out = (TextView)findViewById(R.id.out);
in = (EditText)findViewById(R.id.input);
/*****************************************************/
set.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
setcontent();
}
});
}

Related

App crash after button click [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I tried creating a simple app "MemeCrater" which i learned from one of youtube tutorial.but whenever i press the Create button.The App crashes.
This is the error i get.
Error
Process: com.example.iemshekhar.memegenerator, PID: 13118
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.iemshekhar.memegenerator.TopSectionFragment$TopSectionListener.createMeme(java.lang.String, java.lang.String)' on a null object reference
at com.example.iemshekhar.memegenerator.TopSectionFragment.buttonClicked(TopSectionFragment.java:57)
at com.example.iemshekhar.memegenerator.TopSectionFragment$1.onClick(TopSectionFragment.java:49)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is my main activity java file:
MainActivity.java
package com.example.iemshekhar.memegenerator;
import android.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements TopSectionFragment.TopSectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void createMeme(String top, String bottom) {
BottomPictureFragment bottmfragment=(BottomPictureFragment)getFragmentManager().findFragmentById(R.id.fragment2);
bottmfragment.setMemeText(top,bottom);
}
#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);
}
}
This is my top Fragement java file:
TopSectionFragment.java
package com.example.iemshekhar.memegenerator;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TopSectionFragment extends Fragment {
private static EditText top, bottom;
TopSectionListener activitycommander;
public interface TopSectionListener{
public void createMeme(String top,String bottom);
}
public void onAtttach(Context context)
{
try{
activitycommander=(TopSectionListener)context;
}
catch(ClassCastException e){
throw new ClassCastException(e.getMessage());
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
top = (EditText)view.findViewById(R.id.toptextinput);
bottom = (EditText) view.findViewById(R.id.bottomtextinput);
final Button create = (Button) view.findViewById(R.id.createbutton);
create.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View v) {
activitycommander.createMeme(top.getText().toString(),bottom.getText().toString());
}
}
This file is my bottom Fragment java File:
BottomSectionFragment.java
package com.example.iemshekhar.memegenerator;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by IEmShekhar on 6/18/2016.
*/
public class BottomPictureFragment extends Fragment {
public static TextView toptext,bottomtext;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_picture_fragment, container, false);
toptext=(TextView)view.findViewById(R.id.textView1);
bottomtext=(TextView)view.findViewById(R.id.textView2);
return view;
}
public void setMemeText(String top,String bottom){
toptext.setText(top);
bottomtext.setText(bottom);
}
}
These are my XML Files:
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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:background="#006669"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="290dp"
android:name="com.example.iemshekhar.memegenerator.BottomPictureFragment"
android:id="#+id/fragment2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/bottom_picture_fragment" />
<fragment
android:layout_width="400dp"
android:layout_height="wrap_content"
android:name="com.example.iemshekhar.memegenerator.TopSectionFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/top_section_fragment"
android:layout_above="#+id/fragment2" />
</RelativeLayout>
Top_section_Fragment.xml
<?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" android:background="#999999">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toptextinput"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:width="300dp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bottomtextinput"
android:layout_centerHorizontal="true"
android:layout_below="#+id/toptextinput"
android:width="300dp"
android:layout_marginTop="30dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerHorizontal="true"
android:text="#string/Create_text"
android:background="#006666"
android:textStyle="bold"
android:id="#+id/createbutton"/>
</RelativeLayout>
Bottom_picture_Fragement.xml
<?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"
android:background="#drawable/afaque">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/toptext"
android:textStyle="bold"
android:textSize="25sp"
android:background="#ffff"
android:width="400dp"
android:textAlignment="center"
android:id="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bottomtext"
android:textStyle="bold"
android:textSize="25sp"
android:background="#ffff"
android:width="400dp"
android:textAlignment="center"
android:id="#+id/textView2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Guessing that you're trying to set the text from editText, You should be accessing the text from your editText in your TopSectionFragment
Replace
//Initialize
`private static TextView top, bottom;`
//onCreateView() Method
top = (TextView) view.findViewById(R.id.textView1);
bottom = (TextView) view.findViewById(R.id.textView2);
with this
//Initialize
`private static EditText top, bottom;`
//onCreateView Method
//onCreateView() Method
top = (EditText) view.findViewById(R.id.toptextinput);
bottom = (EditText) view.findViewById(R.id.bottomtextinput);
in your TopSectionFragment. Hope this will help :)

How to load Myanmar Language in Web View in android?

I have a web view in which i will enter the URL and load that content to that web view.
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"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:visibility="gone" />
<LinearLayout
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/urlField"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:ems="10"
android:inputType="textUri"
android:imeOptions="actionDone"
android:hint="http://proteam.in" />
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="#+id/layout"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:onClick="open"
android:text="#string/browse" />
</LinearLayout>
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentBottom="true"
android:layout_below="#+id/layout" />
</RelativeLayout>
MainActivity.java
package com.example.mayanmarbroswer;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText field;
private WebView browser;
private ProgressDialog pDialog;
final Context context = this;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
field = (EditText)findViewById(R.id.urlField);
browser = (WebView)findViewById(R.id.webView1);
browser.setWebViewClient(new MyBrowser());
//myTextView.setTypeface(typeFace);
WebSettings webSettings = browser.getSettings();
webSettings.setDefaultTextEncodingName("utf-8");
webSettings.setFixedFontFamily("file:///android_asset/font/Sanpya.ttf");
ActionBar bar = getActionBar();
bar.hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
field.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
if (actionId == EditorInfo.IME_ACTION_DONE)
{
if(field.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(), "Enter Valid WebSite", Toast.LENGTH_SHORT).show();
}
else
{
open(v);
}
}
return false;
}
});
}
public void open(View view){
String url;
if(field.getText().toString().trim().equals(""))
{
Toast.makeText(getApplicationContext(), "Enter Valid WebSite", Toast.LENGTH_SHORT).show();
}
else
{
if(field.getText().toString().startsWith("http://"))
{
url = field.getText().toString();
}
else
{
url = "http://" + field.getText().toString();
}
browser.getSettings().setLoadsImagesAutomatically(true);
browser.getSettings().setJavaScriptEnabled(true);
browser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
browser.loadUrl(url);
}
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
/*pDialog = new ProgressDialog(context, ProgressDialog.THEME_HOLO_DARK);
// set indeterminate style
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
// set title and message
//pDialog.setTitle("Please wait");
pDialog.setMessage("Loading Pls Wait");
// and show it
pDialog.show();*/
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//do what you want to do
/*if (pDialog.isShowing())
{
pDialog.dismiss();
}*/
}
}
#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;
}
}
URL 1: http://www.mora.gov.mm/
URL 2: http://www.saikwan.info/
i tested this in few android device like moto e (4.4.2), Dell venue 7 (4.4.2), Samsung Duos GT-s7392 (4.1.2) and Videocon z40pro(4.2.2) the above given URL with myanmar font is working correctly. but when i try to load that in Samsung GT-s7582(4.2.2) the myanmar fonts are missing in web view. so, please let me know how to solve this issue.
If you fetch data from resource folder i mean asset folder then try this way.
Java Code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonPlayVideo = (Button)findViewById(R.id.playvideoplayer);
Button buttonPlayVideo1 = (Button)findViewById(R.id.button1);
Button acceess = (Button)findViewById(R.id.button2);
getWindow().setFormat(PixelFormat.UNKNOWN);
//Displays a video file.
buttonPlayVideo1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// VideoView refference see main.xml
VideoView mVideoView = (VideoView)findViewById(R.id.videoview);
//String uriPath = "android.resource://com.android.AndroidVideoPlayer/"+R.raw.k;
String uriPath = "android.resource://com.android.AndroidVideoPlayer/"+R.raw.demo;
Uri uri = Uri.parse(uriPath);
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();
}
});
If you fetch from URL or FTP Server OR HTTP Connection then try this way
Java Page
buttonPlayVideo.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//VideoView mVideoView = (VideoView)findViewById(R.id.videoview);
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://192.168.0.8/aeon/")); // For Video Content
// new Intent(Intent.ACTION_VIEW, Uri.parse("ftp://movies:movies#192.168.0.8/Transport_Streams/"));
startActivity(browserIntent);
}});
acceess.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(AndroidVideoPlayer.this,Videopage.class);
startActivity(i);
}
});
}
XML Code Of Both Way are is Given Following way
XML Page for when fetch from the resource
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FF8800"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Welcome To Aeon Group"
android:textColor="#9933CC"
android:textSize="3mm" />
<VideoView
android:id="#+id/videoview"
android:layout_width="fill_parent"
android:layout_height="394dp"
android:layout_above="#+id/playvideoplayer"
android:layout_alignParentLeft="true" />
<Button
android:id="#+id/playvideoplayer"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="22dp"
android:background="#drawable/button"
android:text="Aeon Content" />
<!-- <VideoView
android:id="#+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/playvideoplayer"
android:layout_below="#+id/textView1" />
-->
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/playvideoplayer"
android:layout_alignBottom="#+id/playvideoplayer"
android:layout_alignParentLeft="true"
android:background="#drawable/button"
android:text="Play" />
<Button
android:id="#+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/playvideoplayer"
android:layout_alignBottom="#+id/playvideoplayer"
android:layout_toRightOf="#+id/playvideoplayer"
android:background="#drawable/button"
android:text="Acces" />
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

ParseUser search

I am trying to create a simple user search page for my app. I tried to create a ParseQuery and display results in a Listview in my main activity page. However, when I run program, I could not get a result of a search, program displays nothing. I will be happy if I get an answer.
Here is my MainActivity.java;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.results);
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.activity_main, R.layout.search_list );
//mainAdapter.setTextKey("username");
userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
uName = searchArea.getText().toString();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
mainAdapter.add((ParseUser)objects.get(i));
}
} else {
// Something went wrong.
e.printStackTrace();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#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);
}
}
And my main activity xml file;
<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.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/results"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp" >
</ListView>
</RelativeLayout>
I solved this problem. Here is updated version of code;
package com.example.searchtest;
import java.util.ArrayList;
import java.util.List;
import com.parse.*;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Button search;
private EditText searchArea;
private ListView userList;
//private String uName;
private ArrayAdapter<ParseUser> mainAdapter;
private ArrayList<ParseUser> resultList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Parse.initialize(this, "WHz2GmkGFIUxBir6ZEDt2FIG4WUcE1kfKZmPayxy", "IAs1RCaRt5LM1E1ZW7LFXy5uDjtZEQ5CDa3LKJt2");
setContentView(R.layout.activity_main);
search = (Button) findViewById(R.id.searchButton);
searchArea = (EditText) findViewById(R.id.searchField);
userList = (ListView) findViewById(R.id.userResultList);
resultList = new ArrayList<ParseUser>();
mainAdapter = new ArrayAdapter<ParseUser>(this, R.layout.list_item, R.id.user_results,resultList);
//mainAdapter.setTextKey("username");
//userList.setAdapter(mainAdapter);
//mainAdapter.loadObjects();
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String uName = searchArea.getText().toString();
final ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", uName);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> objects, ParseException e) {
if (e == null) {
for(int i=0; i<objects.size();i++)
{
resultList.add((ParseUser)objects.get(i));
}
userList.setAdapter(mainAdapter);
Toast.makeText(getApplicationContext(), "User is Found",
Toast.LENGTH_LONG).show();
} else {
// Something went wrong.
e.printStackTrace();
Toast.makeText(getApplicationContext(), "User is not Found",
Toast.LENGTH_LONG).show();
}
}
});
userList.setAdapter(mainAdapter);
}
});
}
#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);
}
}
Moreover I need one more xml file to display the list. it is list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/user_results"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
and main xml file, 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.searchtest.MainActivity" >
<EditText
android:id="#+id/searchField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="29dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/searchButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editText1"
android:layout_alignParentRight="true"
android:text="Search" />
<ListView
android:id="#+id/userResultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/searchField"
android:layout_below="#+id/searchField"
android:layout_marginTop="39dp" >
</ListView>
</RelativeLayout>
put uName = searchArea.getText().toString(); inside the listener, you are setting uName only once when the view is created, so it will be empty. You need to get the text after the user enters input and the button is clicked.

Access to Browser history on Android Application

I have created a simple browser application with a edittext , go button and history button.
Please suggest what coding do i need to implement for history button such that when i press it my browsing history gets displayed on the hi.xml layout. Please suggest what coding changes do i need to make in my xml file as well as java file .
MainActivity.java:
package com.example.history;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener{
EditText t;
Button g,h;
WebView w;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g=(Button) findViewById(R.id.button1);
h=(Button) findViewById(R.id.button2);
t=(EditText) findViewById(R.id.editText1);
w=(WebView) findViewById(R.id.webView1);
h.setOnClickListener(this);
g.setOnClickListener(this);
w.getSettings().setJavaScriptEnabled(true);
w.getSettings().setLoadWithOverviewMode(true);
w.getSettings().setUseWideViewPort(true);
w.setWebViewClient(new Callback());
}
#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 void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId())
{
case R.id.button1:
String c;
c=t.getText().toString();
String theWebsite=("http://").concat(c);
t.setText(theWebsite);
w.loadUrl(theWebsite);
InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(w.getWindowToken(),0);
break;
case R.id.button2:
Intent a=new Intent(MainActivity.this,h.class);
startActivity(a);
break;
}
}
}
class Callback extends WebViewClient{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (false);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginLeft="15dp"
android:layout_marginTop="16dp"
android:ems="10" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_marginTop="34dp"
android:layout_toRightOf="#+id/textView1"
android:text="Go" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button1"
android:layout_centerVertical="true"
android:text="History" />
<WebView
android:id="#+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
h.java:
package com.example.history;
import android.app.Activity;
import android.os.Bundle;
public class h extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.hi);
}
}
hi.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
When you open a URL using the WebView it gets stored in the phone's web history.
You can access it by using the below code.Later add it to the listview you use in hi.xml
try{
Cursor mCur = null;
try{
String sortOrder = Browser.BookmarkColumns.DATE + " ASC";
mCur= context.getContentResolver().query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, null, null, sortOrder);
mCur.moveToFirst();
if (mCur.moveToFirst() && mCur.getCount() > 0) {
while (mCur.isAfterLast() == false) {
String title = mCur.getString(Browser.HISTORY_PROJECTION_TITLE_INDEX);
String url = mCur.getString(Browser.HISTORY_PROJECTION_URL_INDEX);
long date = mCur.getLong(Browser.HISTORY_PROJECTION_DATE_INDEX);
mCur.moveToNext();
}
}else{
mCur.close();
}
}catch(Exception e){
}finally{
mCur.close();
}
}catch(Exception e){
}
Also you need to give the below permission in your manifest file. Hope this helps.
<uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
You need to implement the onPageFinished Method on the WebView Client Class
and you need to save your loaded url to the localdatabase or if you want that history for perticular session of the app then you can also use the other structure like arraylist...
class Callback extends WebViewClient{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (false);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
/// Save the url to the localdatabase or to any structure if you want temporary
}
}
and while user press on the history button you need to fetch the data from localdatabase to cursor
and use cursoradapter to display the list of the history url
If you have any further doubt then feel free to ask me...

My app has crashed android eclipse?

I get an error when I run my android app on my android device. It says Unfortunately, GuessingGame has stopped. It was running before but ever since I added a EditText to the layout, it has been crashing. Here is my MainActivity.java:
package com.h2ogaming.numberguessinggame;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView1);
Button pressMe = (Button) findViewById(R.id.button1);
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
// TODO Auto-generated method stub
Random randGen = new Random();
int random = randGen.nextInt(5) + 1;
randText = Integer.toString(random);
textOne.setText(randText);
}
});
}
#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;
}
}
Here is my Activity_Main XML file:
<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=".MainActivity"
android:background="#2288ee">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="79dp"
android:text="#string/guess_text"
android:textColor="#ffffff"
android:textSize="26sp" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="#string/text_view1"
android:textColor="#ffffff"
android:textSize="26sp" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:text="#string/btn_press" />
</RelativeLayout>
Please help me. Thanks!
Change your initialization for components.declare proper all components globally. then initialize it like below code:
public class MainActivity extends Activity {
TextView textOne;
Button pressMe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textOne = (TextView) findViewById(R.id.textView1);
pressMe = (Button) findViewById(R.id.button1);

Categories